0% found this document useful (0 votes)
8 views31 pages

Inheritance

Uploaded by

jackson lymo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Inheritance

Uploaded by

jackson lymo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Inheritance

Introduction

Inheritance is a mechanism that enables one
class to inherit all the behaviour and
attributes of another class.

Through inheritance, a class immediately
has all the functionality of an existing class.
Because of this, you must define only how
the new class is different from an existing
class.

Inheritance is one of the primary features of
OOP — which is a form of software reuse.
© K.S. Mbise Inheritance Slide 2
Introduction cont...
 A class that is inherited is called superclass
 The class that inherits is called subclass
 A subclass is a specialized version of a
superclass
 extends – (or “inherits from”) keyword is used
to inherit superclass
 Java does not support multiple superclasses into
single subclass (this differs from C++)
 A subclass can be a superclass of another
subclass
© K.S. Mbise Inheritance Slide 3
Inheritance example
//create superclass
public class A {
int x,y;
void showXY(){
System.out.println("x and y: "+x+ "
"+y);
}
}
© K.S. Mbise Inheritance Slide 4
Inheritance example
cont…
//create subclass by extending class A
class B extends A{
int z;
void showZ(){
System.out.println("k: "+z);
}
void sum(){
int sum=x+y+z;
System.out.println("sum: "+sum);
}
}

© K.S. Mbise Inheritance Slide 5


Inheritance example
cont…
class ABTest{
public static void main(String[] args){
A superObj=new A();
B subObj=new B();
//The superclass may be used by itself
superObj.x=10;
superObj.y=20;
System.out.println("Contents of the superObj");
superObj.showXY();
System.out.println();

© K.S. Mbise Inheritance Slide 6


Inheritance example
cont…
//The subclass has access to all public members of its superclass
subObj.x=7;
subObj.y=8;
subObj.z=9;
System.out.println("Contents of the subObj");
subObj.showXY();
subObj.showZ();
System.out.println();
System.out.println("The sum of x, y, and z in subObj");
subObj.sum();
}
}
© K.S. Mbise Inheritance Slide 7
Inheritance and member
access
• A subclass cannot access those members
of the superclass that have been declared
as private.
• A class’s private members are accessible
only from within the class itself.
• A subclass can change the state of private
superclass instance variables only through
non-private methods provided in the
superclass and inherited by the subclass.

© K.S. Mbise Inheritance Slide 8


Inheritance and member
access cont…
public class X {
int number1, number2;
private int number3;
void setNumber3(int number){
number3=number;
}
int getNumber3(){
return number3;
}
}

© K.S. Mbise Inheritance Slide 9


Inheritance and member
access cont…
class Y extends X{
void sum(){
int
sum=number1+number2+super.getNumber3();
/*error - number3 is not directly accessible,
instead use get method as done here!*/
System.out.println(sum);
}
}

© K.S. Mbise Inheritance Slide 10


Inheritance and member
access cont…
class XYTest{
public static void main(String[] args){
Y y=new Y();
y.number1=4;
y.number2=8;
y.setNumber3(9);
y.sum();
}//Note – two classes must be in different
packages
}
© K.S. Mbise Inheritance Slide 11
Box example
 A Box class has three instance variables
width, height and depth and one member
method volume. It also has different
formats of constructor methods to
initialize the instance variables, such as
 Through parameters w, h and d
 No parameter
 Single parameter length of each side
 A BoxWeight class that has all the
properties of Box except another instance
variable weight. To initialize this variable,
it needs constructor
© K.S. Mbise Inheritance Slide 12
Box example cont…
 Another class ColorBox has all the
properties of Box except another
property color
 Write down the structures of these
three classes (ColorBox left as an
assignment)
 The example in the class will
include the two classes only i.e.,
Box and weightBox.
© K.S. Mbise Inheritance Slide 13
Using super keyword
 If a superclass keeps its data members
private, then there would be no way for
subclass to directly access or initialize
its parent's instance variables
 The solution is the use of keyword super
 Whenever a subclass needs to refer to
its immediate superclass, it can do so by
use of the keyword super
 Super has two general forms,
 For accessing constructors
 For accessing hidden member of superclass
© K.S. Mbise Inheritance Slide 14
Using super to call superclass
constructors
 super (parameter-list)
 super( ) must always be the first statement
executed inside a subclass’ constructor
// BoxWeight now uses super to initialize its Box
attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
© K.S. Mbise Inheritance Slide 15
Box example
//superclass Box
public class Box {
float length,width,depth;
public Box(float l,float w,float d){
length=l;
width=w;
depth=d;
}
float volume(){
return length*width*depth;
}
}//end superclass Box

© K.S. Mbise Inheritance Slide 16


Box example cont…
class BoxWeight extends Box{
float weight;
BoxWeight(float l, float w, float d, float wt){
//initializing constructor of subclass using super
super(l,w,d);
weight=wt;
}
float volumeWeightBox(){
return super.volume();
}
}//end subclass BoxWeight

© K.S. Mbise Inheritance Slide 17


Box example cont…
class BoxTest{
public static void main(String[] args){
Box eb=new Box(5,4,3);
BoxWeight wb=new BoxWeight(5,4,3,12);

System.out.println("Empty box details");


System.out.println("The volume is "+eb.volume());

System.out.println("\nWeighing box details");


System.out.println("The volume is "+wb.volumeWeightBox());
System.out.println("The weight is "+wb.weight);

© K.S. Mbise Inheritance Slide 18


Box example cont…
System.out.println("\nInstances of the two boxes details");
System.out.println("Is an object of subclass object of
superclass? "
+(wb instanceof Box));
System.out.println("Is an object of superclass object
of subclass? "
+(eb instanceof BoxWeight));
}//end method main
}//end class BoxTest

© K.S. Mbise Inheritance Slide 19


A second use for super
• Here super acts as somewhat like this.
• Mostly applicable when member names
of a subclass hide members by the
same name in the superclass.
• This practice is also known as variable
shadowing. Shadowing refers to the
practice of using two variables with the
same name within scopes that overlap.
• The higher-level scope is hidden
because the variable with lower-level
scope overrides it.
© K.S. Mbise Inheritance Slide 20
Method overriding
 When a method in a subclass has the
same name and type signature as a
method in its superclass, then the
method in the subclass is said to
override the method in the superclass.
 When an overridden method is called
from within a subclass, it will always
refer to the version of that method
defined by the subclass.

© K.S. Mbise Inheritance Slide 21


Method overriding cont…
public class Number {
int number1, number2;
void showNumbers(){
//display number1 and number2
System.out.println("number1 and
number2: "+number1+" "+number2);
}
}
© K.S. Mbise Inheritance Slide 22
Method overriding cont…
class MoreNumber extends Number{
int number3;
//display number3 - this overrides
showNumbers() in Number
void showNumbers(){
System.out.println("number3: "+number3);
}
}

© K.S. Mbise Inheritance Slide 23


Method overriding cont…
class NumberTest{
public static void main(String[] args){
MoreNumber mn=new MoreNumber();
mn.number1=1;
mn.number2=2;
mn.number3=4;
mn.showNumbers();
}
}
© K.S. Mbise Inheritance Slide 24
Method overriding cont…
• Accessing superclass version of
overridden method using super keyword.
• E.g.,
void showNumbers(){
super.showNumbers();//this solves
the problem of overriding
System.out.println("number3:
"+number3);
}
© K.S. Mbise Inheritance Slide 25
Using final to prevent
overriding
 Methods declared as final cannot be
overridden
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
© K.S. Mbise Inheritance Slide 26
Using final to prevent
overriding cont…
 Normally Java resolves calls to
methods dynamically, at run time
(late binding)
 Since, final methods cannot be
overridden, a call to one can be
resolved at compile time (early
binding).

© K.S. Mbise Inheritance Slide 27


Overriding vs.
overloading
 Method overriding occurs only
when the names and the type
signatures of the two methods are
identical.
 Method overloading occurs when
the names of two or more
methods are the same within the
class but different signatures.

© K.S. Mbise Inheritance Slide 28


Using final to prevent
inheritance
 final keyword before a class declaration
prevents it from being inherited.
 Declaring a class as final implicitly declares all
of its methods as final
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}

© K.S. Mbise Inheritance Slide 29


The Object class
 Object class is a special type of class defined
by Java
 All other classes are subclasses of Object
 A reference variable of type object can refer
to an object of any other class
 Objects define the following methods:
 Object clone( )
 boolean equals (Object object)
 void finalize( )
 class getClass( )
 String toString( )
 void wait(long milliseconds)
© K.S. Mbise Inheritance Slide 30
Thank you for listening!

© K.S. Mbise Inheritance Slide 31

You might also like