Oops Unit 2 Theoritical Points
Oops Unit 2 Theoritical Points
-
The keyword used for inheritance is extends.
Syntax:
Class Sub-classname extends Super-classname
{
Declaration of variables;
Declaration of methods;
}
Example:
class Circle
{ Circle() { }
private int radius;
void setRadius(int radius){
this.radius= radius; class SimpleInheritance {
} public static void main(String args[])
int getRadius(){ { double vol;
return this.radius; Cone cn=new Cone();
} cn. setRadius(5);
double computeArea(){ cn.setHeight(10);
return (3.141*this.radius*this.radius); vol=cn.volume();
} System.out.println(vol);
double comutePerimeter(){ }
return 2*3.141*this.radius; }
} As you can see ,sub class Cone can access methods of Circle but
} not data member, because radius of super class is declared as
class Cone extends Circle{ private. sub class can’t inherit the private properties of super
int height; class.
Cone() { }
void setHeight(int height){
this.height= height;
}
int getHeight(){
return this.height;
}
double volume(){
double v=(this.computeArea() *this.height )/3;
return v;
}
}
What You Can Do in a Subclass
A subclass inherits all of the public, defult and protected members of its parent. The inherited fields can be used directly, just like
any other fields.
You can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
You can declare new methods in the subclass that are not in the superclass.
You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the
keyword super.
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for
accessing its private fields, these can also be used by the subclass.
Types of
inheritance :
• Single
• Hierarchica C
l
• Multiple
• Multilevel
• Hybrid C
B C
Single Inheritance : In single inheritance, subclass inherits features of superclass. In image below, the class A serves as a
super class for the sub class B
Exampl Person
e
Employ
ee
Exampl
e
2.Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.
Person
Employ Student
ee
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a super class and as well as the derived class also act as the base class to other
class. In below image, the class A serves as a super class for the derived class B, which in turn serves as a super class for the derived class C.
Person
Employ
ee
Manage
Example 2 Example 3
Important facts about inheritance in Java
Default superclass: Except Object class, which has no superclass, every class has one and only one direct
superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a
subclass of Object class.
Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have
only one superclass. This is because Java does not support multiple inheritance with classes. Although with
interfaces, multiple inheritance is supported by java.
Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its parent class. However,
if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these
can also be used by the subclass.
Super Keyword in Java
The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the
picture with the concept of Inheritance. It is majorly used in the following contexts:
Use of super with variables: This scenario occurs when a derived class and base class has same data members. In that case
there is a possibility of ambiguity . We can understand it more clearly using this code snippet:
class vehicle */
class Vehicle
{
int maxSpeed = 120;
} In this example, both base class and subclass have
a member maxSpeed. We could access maxSpeed
/* sub class Car extending vehicle */
class Car extends Vehicle of base class in sublcass using super keyword.
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
Class B extends A{
• Example double j;
B() { }
B(double I,double j){
class A super(i);
{ double i; this.i=i;
A() { } }
A(double i){ void show()// this method overrides{
this.i=i; System.out.println(“i=“+i);
} System.out.println(“j=“+j);
void show(){ }
System.out.println(“i=“+i); Public class Mainclass{
} public static void main(String[] args){
} B obj= new B();
obj.show();
}
}
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
Method overriding forms the basis for one of Java’s most powerful concept: dynamic method
dispatch.
In inheritance a superclass reference variable can refer to a subclass object. Java uses this fact to
resolve calls to overridden methods at run time. When an overridden method is called through a
superclass reference, Java determines which version of that method to execute based upon the type
of the object being referred to at the time the call occurs. Thus, this decision is made at run time.
When different types of objects are referred to, different versions of an overridden method will be
called.
Dynamic Method Dispatch Example:
This program creates one superclass called A and sub class B .
Subclasses B override show( ) declared in A. Inside the main( ) method, a reference of type A, called
obj , is declared. The program then in turn assigns a reference to each type of object to obj and uses
that reference to invoke show( ). As the output shows, the version of show( ) executed is determined by
the type of object being referred to at the time of the call.
Class B extends A{
Example double k;
B() { }
B(double I, double j){
super(i);
class A this.i=i;
{ double i; }
void show()// this method overrides{
A() { }
System.out.println(“i=“+i);
A(double i){ System.out.println(“j=“+j);
this.i=i; }
} Public class Mainclass{
public static void main(String[] args){
void show(){
A obj;
System.out.println(“i=“+i); obj= new A();
} obj.show();
} obj=new B();
obj.show();
}
}
Polymorphism:
Polymorphism is essential to object-oriented programming for one reason: it allows a general class to
specify methods that will be common to all of its derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods. Overridden methods allow Java to support
run-time polymorphism.
Dynamic or run-time polymorphism is one of the most powerful mechanisms that object oriented
design brings to bear on code reuse and robustness.
In Java, compile time polymorphism occurs through method overloading and dynamic
polymorphism occurs when a parent class reference is used to refer to a child class object.
Let’s look at a practical example that uses method overriding to achieve run_time polymorphism. The
following program creates a superclass called Bank that contains members related to bank . It
defines a methods called deposit( ) and withdraw() . The program derives two subclasses from
Bank. The first is SBI and the second is HDFC. Each of these subclasses overrides withdraw( )
method Note:
to have their
Write specificprogram
concerned defintions
here
Abstract classes and Abstract methods
An abstract class captures common characteristics of subclasses and may or may not contain any abstract
method. It cannot be instantiated but can be used as a superclass .
An abstract method is a method that is declared without an implementation.
An abstract method is declared like this:
abstract returntype methodname(Parameterlist);
An abstract class is declared like this:
accessmodifier abstract className {
// declare fields
// declare abstract methods
//define non abstract methods
}
If a class includes abstract methods, then the class itself must be declared as abstract.
We use abstract classes if any of these statements apply to your situation:
You want to share base code among several closely related classes.
If certain methods of class need to be made as abstract .
You expect that classes that extend your abstract class have many common methods or fields,
or require access modifiers other than public (such as protected and private) .
--
abstract Employee
Empno
Name Note: Write something
Employee() about this example
diplayEmpData()
abstract calculateSalary()
Monthly_Based_Employee Contract_Based_Employee
Basicpay NoOfHours,wage
Monthly_Based_Employee(- Contract_Based_Employee(---
------) --------)
calculateSalary() calculateSalary()
import java.util.Scanner;
abstract class Employee{ class CBEmployee extends Employee
private int Empno; private String Name; { double Nohours,hourlyWage, Netsalary;
Employee(int Empno, String Name){ CBEmployee(int eno, String Name,double NH, double
this.Empno=Empno; this.Name=Name; HW){
} super(eno, Name);
void displayEmpData(){ Nohours=NH;
System.out.println("Employee no"+Empno); hourlyWage=HW;
System.out.println("Name"+Name); }
} void calculateSalary(){
abstract void calculateSalary(); Netsalary=Nohours*hourlyWage;
}//EMP CLASS CLASE }
class MBEmployee extends Employee void CBdisplay(){
{ double BasicPay, Netsalary; displayEmpData();
MBEmployee(int eno, String name, double bp){ System.out.println("Total salary"+Netsalary);
super(eno,name); BasicPay=bp; }
} }// Teacher close
void calculateSalary(){
if(BasicPay>=10000) public class AbstractDemo{
Netsalary=BasicPay+(BasicPay*20/100.0) +(BasicPay*50/100.0)- public static void main(String[] args){
(BaiscPay*18/100.0); MBEmployee ME=new MBEmployee(101,”KAPIL”, 20000);
else CBEmployee CE=new CBEmployee(201, “LAYA”, 30,200);
Netsalary=BasicPay+(BasicPay*15/100.0) +(BasicPay*75/100.0) - ME.calculateSalary();
(BaiscPay*12/100.0); CE.calculateSalary();
} ME.MBdisplay();
void MBdisplay(){ CE.CBdisplay();
displayEmpData(); }
System.out.println("Employee no"+Netsalary); }
}}
Interface
Interface is a complete abstract class.
Using interface ;you can specify what a class must do, but not how it does it. Interfaces are syntactically like classes, but
they lack instance variables, and their methods are declared without any body.
In practice, this means that you can define interfaces that don’t make assumptions about how they are implemented. Once it
is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is
free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize
the “one interface, multiple methods” aspect of polymorphism.
An interface is defined much like a class. This is the general form of an interface:
accessmodifier interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
All methods in an interface are public abstract. All interface variables are public static final
Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include
the implements clause in a class definition, and then create methods defined by the interface. The general form of a class
that includes the implements clause looks like this:
Example:
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain. Following
is an example: class MyClass implements B {
public void meth1() {
interface A {
System.out.println("Implement meth1().");
void meth1(); }
void meth2(); public void meth2() {
} System.out.println("Implement meth2().");
}
public void meth3() {
interface B extends A { System.out.println("Implement meth3().");
void meth3(); }
} }
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Multiple inheritance in Java by interface
In Java a class can implements multiple interfaces, or an interface extends multiple interfaces .
Example:
final variable
Final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized. Lets have a look at the below code: In this program MAX_VALUE is the final variable.
class Demo{
final int MAX_VALUE=99;
void myMethod(){
System.out.pritln(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
final method
A final method can be inheritance but cannot be overridden. Which means even though a sub
class can call the final method of parent class without any issues but it cannot override it.
Example:
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
When a program needs any package, it is to be imported. for example when we need user input, we
import a package like this:
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Before we see how to create a user-defined package in java, lets see the advantages of using a package.
2.CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command: SET CLASSPATH
3. Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath
or -cp of the javac and java commands, for example,