0% found this document useful (0 votes)
430 views38 pages

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

The document discusses inheritance in Java including single, multi-level, multiple, hierarchical and hybrid inheritance. It covers method overriding, the super keyword, abstract classes and provides code examples of inheritance concepts.
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)
430 views38 pages

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

The document discusses inheritance in Java including single, multi-level, multiple, hierarchical and hybrid inheritance. It covers method overriding, the super keyword, abstract classes and provides code examples of inheritance concepts.
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/ 38

Programming in Java, 2e

Sachin Malhotra
Saurabh Choudhary
Chapter 3

Inheritance
Objectives
• Know the difference between Inheritance and
aggregation
• Understand how inheritance is done in Java
• Learn polymorphism through Method
Overriding
• Learn the keywords : super and final
• Understand the basics of abstract class.
Inheritance
• Is the ability to derive something specific from
something generic.
• aids in the reuse of code.
• A class can inherit the features of another class and
add its own modification.
• The parent class is the super class and the child class
is known as the subclass.
• A subclass inherits all the properties and methods of
the super class.
Inheritance
Aggregation
• We can make up objects out of other objects.
• The behaviour of the bigger object is defined by the
behaviour of its component objects, separately and
in conjunction with each other.
• cars contain engine which in turn contains an ignition
system and starter motor.
• a whole-part relationship exists in aggregation
• car being the whole and engine being its part.
Types of Inheritance

• Single
• Multiple
• Multilevel
• Hierarchical
• Hybrid
Single level inheritance
Classes have only base class
Multi level
There is no limit to this chain of inheritance (as
shown below) but getting down deeper to four or
five levels makes code excessively complex.
Multiple Inheritance
A class can inherit from more than one unrelated
class
Hierarchical Inheritance

• In hierarchical inheritance, more than one


class can inherit from a single class. Class C
inherits from both A and B.
Hybrid Inheritance

• is any combination of the above defined


inheritances
Deriving Classes
• Classes are inherited from other class by declaring
them as a part of its definition
• For e.g.
– class MySubClass extends MySuperClass
• extends keyword declares that MySubClass inherits
the parent class MySuperClass.
Inheritance
Method Overriding
• 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.
• it is a feature that supports polymorphism.
• When an overridden method is called through the
subclass object, it will always refer to the version of
the method defined by the subclass.
• The superclass version of the method is hidden.
Superclass Can Refer to a Subclass
Object
The real power of overriding is illustrated by the
following code. A super class reference
variable can be assigned a subclass object.

E.g. in the example of method overriding we can


create an object of class A by referring
subclass B as follows,
AClass a = new BClass();
a.doOverride();
super Keyword

The “super” keyword refers to the parent class


of the class in which the keyword is used. It is
used for following three purposes,

• For calling the methods of the super class.


• For accessing the member variables of the super
class.
• For invoking the constructors of the super class.
super Keyword (contd.)
class A
{
void show()
{
System.out.println(“Super Class show method”);
}
}
class B extends A
{
void show()
{
System.out.println(“Sub Class show method”);
}
public static void main (String args[ ])
{
A s1=new A();
s1.show();
B s2=new B ();
s2.show();
}
Problem and Solution

• o/p=> Super Class show method


Sub Class show method
• Two methods show() and overridden show()
are being called by two different objects A and
B , instead the job can be done by one object
only, i.e. using super keyword.
Case 1: Invoking Methods using super
import java.io.*;
class Anew
{
void show()
{
System.out.println(“Super Class show method”);
}
}
class BNew extends Anew
{
void show()
{
super.show();
System.out.println(“Sub Class show method”);
}
public static void main (String args[ ])
{
BNew s2=new BNew ();
s2.show();
}
}
OUTPUT
• => Super Class show method
Sub Class show method
Case 2: Accessing variables using super
import java.io.*;
class Super_Variable
{
int b=30;
}
class Sub_Class extends Super_Variable
{
int b=12;
void show()
{
System.out.println("subclass class variable: "+ b);
System.out.println("superclass instance variable: "+super.b);
}
public static void main (String args[])
{
Sub_Class s=new Sub_Class();
s.show();
}
}
The output

• subclass class variable: 12


• superclass instance variable: 30
Case 3: constructors of the super class.
import java.io.*;
class Constructor_A
{
Constructor_A()
{
System.out.println("Constructor A");
}
}
class Constructor_B extends Constructor_A
{
Constructor_B()
{
System.out.println("Constructor B");
}
}
class Constructor_C extends Constructor_B
{
Constructor_C()
{
System.out.println("Constructor C");
}
public static void main (String args[])
{
Constructor_C c=new Constructor_C();
}
}
The Output

Constructor A
Constructor B
Constructor C
Case 3: (contd.)
import java.io.*;
class Constructor_A_Revised
{
Constructor_A_Revised()
{
System.out.println("Constructor A Revised");
}
}
class Constructor_B_Revised extends Constructor_A_Revised
{
Constructor_B_Revised()
{
System.out.println("Constructor B");
}
Constructor_B_Revised(int a)
{
a++;
System.out.println("Constructor B Revised "+ a );
}
}
class Constructor_C_Revised extends Constructor_B_Revised
{
Constructor_C_Revised()
{
super(11);
System.out.println("Constructor C Revised");
}
public static void main (String args[])
{
Constructor_C_Revised a=new Constructor_C_Revised();
}
}
The Output

Constructor A Revised
Constructor B Revised 12
Constructor C Revised
final keyword
• Declaring constants (used with variable and
argument declaration)
– E.g. final int MAX=100;
• Disallowing method overriding (used with method
declaration)
– final void show (final int x)
{
// statements
}
• Disallowing inheritance (used with class declaration).
– final class Demo
{
//statements
}
Your Turn

• What is method overriding?


• Highlight the usage of super keyword?
• What are the usages of final keyword?
• What is late binding and early binding?
Abstract class
• Abstract classes are classes with a generic concept,
not related to a specific class.
• Abstract classes define partial behaviour and leave
the rest for the subclasses to provide.
• contain one or more abstract methods.
• abstract method contains no implementation, i.e. no
body.
• Abstract classes cannot be instantiated, but they can
have reference variable.
• If the subclasses does not override the abstract
methods of the abstract class, then it is mandatory
for the subclasses to tag itself as abstract.
© Oxford University Press 2013. All rights reserved.
Need of creating abstract method

• to force same name and signature pattern in all the


subclasses
• subclasses should not use their own naming patterns
• They should have the flexibility to code these
methods with their own specific requirements.

© Oxford University Press 2013. All rights reserved.


Example of Abstract class
abstract class Animal
{
String name;
String species;
void AnimalName(String n)
{
name=n;
System.out.println("Animal is "+name);
}
void AnimalEat(String fooditem)
{
System.out.println(name + " likes to have "+ fooditem);
}
abstract void AnimalSound(String sound);
}
class Lion extends Animal
{
void AnimalSound(String sound)
{
System.out.println(name+" always "+sound);
}
public static void main(String args[])
{
Lion a=new Lion();
a.AnimalName("Lion");
a.AnimalEat("meat");
a.AnimalSound("Roar");
}
}
© Oxford University Press 2013. All rights reserved.
Practical Problem: Circle class
class Circle {
float radius;
final fl oat PI = 3.141f; //value of pi is fi xed
Circle(){
radius = 1.0f;}
Circle(fl oat radius) {
this.radius = radius;}
float getArea() {
return PI * radius * radius; }}

© Oxford University Press 2013. All rights reserved.


Practical problem: Cylinder class
class Cylinder extends Circle {
float height;
Cylinder(fl oat radius, fl oat height){
super(radius);
this.height = height;
}
float getArea() {
return 2 * super.getArea() + 2 * PI * radius *
height; } © Oxford University Press 2013. All rights reserved.
Practical problem
public static void main(String args[]) {
Circle c = new Circle(1.5f);
System.out.println("The Area of Circle is: " +
c.getArea());
Cylinder cy = new Cylinder(1.5f,3.5f);
System.out.println("The Surface Area of Cylinder
is: " + cy.getArea());
}}

© Oxford University Press 2013. All rights reserved.


Summary
• The concept of Inheritance is derived from real life.
• The properties and methods of a parent class are inherited by
the children or subclasses.
• Subclasses can provide new implementation of method using
method overriding, keeping the method names and
signatures same as that of the parent class.
• The super keyword can be used to access the overridden
methods, variables and even the constructors of the super
class.
• Abstract classes are used to force the subclasses to override
abstract methods and provide body and code for them.
• The final keyword is used to create constants and disallow
inheritance.

© Oxford University Press 2013. All rights reserved.


• Q.1 what will happen when you run the following code.

class Demo
{
Demo(int i)
{
System.out.println(“Demo”);
}
}
class InnerClass extends Demo
{
public static void main(String args[])
{
InnerClass s=new InnerClass();
}
void InnerClass()
{
System.out.println(“Inner Class”);
}
} © Oxford University Press 2013. All rights reserved.
a) Compilation and output of string is “Inner Class ” at
run time.
b) Compile time error
c) Compilation and no output at run time.
d) Compilation and output of string is “Demo”

© Oxford University Press 2013. All rights reserved.

You might also like