6. ClassesAndObjects3
6. ClassesAndObjects3
INHERITANCE
Access Protection
Inheritance
A subclass is a specialized version of a superclass.
A subclass inherits all the instance variables and methods from the
superclass and adds its own unique elements.
class B extends A
{
}
class MyMessage1
class SimpleInheritance
{
{ public static void main(String args[])
void dispMessage1()
{
{
MyMessage2 m2 = new MyMessage2();
System.out.println(“Wel come”);
m2.dispMessage1();
}
m2.dispMessge2()
}
}
class MyMessage2 extends MyMessage1
}
{
void dispMessage2()
{
System.out.println(“MIT, Manipal”);
}
}
class A
{ int i, j;
void showij()
{ System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{ int k;
void showk()
{ System.out.println("k: " + k);
}
void sum()
{ System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{ public static void main(String args[])
{
B subOb = new B();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
subOb.sum();
}
}
Member Access and Inheritance
• The type of the reference variable (not the type of the object) determines what members can
be accessed.
plainbox = weightbox;
vol = plainbox.volume();
System.out.println("Volume of plainbox is " + vol);
The type of the reference variable (not the type of the object) determines what members can
be accessed.
ie, when a reference to a subclass object is assigned to a superclass reference variable, we
will have access to only those parts of the object defined by the superclass.
Hence plainbox can’t access weight even when it refers to a BoxWeight object.
When Constructors Are Called
class A
{ A()
{ System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A
{ B()
{ System.out.println("Inside B's constructor.");
}
}
class C extends B
{ C()
{ System.out.println("Inside C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}
The output from this program is shown here:
A subclass can call a constructor method defined by its superclass by use of the
following form of super:
super(parameter-list);
member of a subclass.
super.member