05 Inheritance
05 Inheritance
INHERITANCE
Circle Cylinder
Circle
-Radius : double -height : double
+ Circle(double r) + Cylinder(double r,
Cylinder + calcArea() : double double l)
The figure shows the relation between Circle and Cylinder classes in an inheritance relationship
Inheritance concept
Inheritance is one-way proposition; a child
inherits from a parent but not the other way
around.
Super class does not have access to the
subclass methods.
When creating a parent class, programmer
does not know how many subclasses are
there and what are their data or methods to
be.
Access Level – Data & Methods
Public
Data and methods can be accessed anywhere class name is
accessible
Private
Data and methods can be accessed within a class.
Protected
behaves similar to private modifier, can only be accessed within a
class but can be extended to be accessed in all subclasses.
// constructor // constructor
public Circle(double r) public Cylinder(double r, double l)
{ radius = r; { super(r);
} length = l;
}
// calculate the area of a circle
public double calcArea() // calculate a volume of cylinder
{ return (PI * radius * radius); public double calcval()
} { return (super.calcArea() * length);
}
public class CalculateCircle
{
public static void main (String[] args)
{
Circle c1 = new Circle(2.50);
Circle c2 = new circle(5.50);
Cylinder c3 = new Cyclinder(3, 4);
C.display();
R.display();
}
}
Overriding Fields and Methods
Overriding Methods
Different methods have the same name
The methods have the same name and parameter
type list and declared in different classes.
They must have the same return types.
A public method can be overridden only by another
public method.
Overriding fields
is similar to overriding methods – they have the same
declarations but in different classes.
Overriding Fields and Methods
public class ClassX public class ClassY extends ClassX
{ {
protected int m; private double n; //overrides field ClassX.n
protected int n;
public void g() //overrides method ClassX.g()
public void f() {
{ System.out.println(“Now in ClassY.g().”);
System.out.println(“Now in ClassX.f() “); n = 3.141678;
m = 22; }
}
public void g() public String toString()
{ //overrides method ClassX.toString()
System.out.println(“Now in ClassX.g(). {
“); return new String(“{ m= “ + m + “, n= “ + n + “}”);
n = 44; }
} }
Public String toString()
{
return new String(“{ m= “ + m + “, n= “ +
n + “}”);
}
}
Overriding Fields and Methods
public class TestClassY
{ OUTPUT :
public static void main (String[] args)
{
ClassX x = new ClassX(); Now in ClassX.f()
x.f(); Now in ClassX.g()
x.g(); x = { m=22, n=44}
System.out.println(“x = “ + x); Now in ClassX.f()
Now in ClassY.g()
ClassY y = new ClassY(); y = {m=22, n=3.141678}
y.f();
y.g();
System.out.println(“y = “ + y);
}
}
Methods Cannot be Overridden