You are on page 1of 92

CHAPTER 6

Inheritance and sub-classing


Contents
• Inheritance
• Super class , sub class
• super keyword
• Method overriding
• Method hiding
• Variable shadowing
• Final keyword
• Instanceof operator
Inheritance in java

In Inheritance one object acquire all


properties and behavior of the parent class
and add new methods and fields

REUSABILITY
Model Number
Color
Weight

extends
Voice command
Roadside Assistance
Airbags
• Suppose you need to define classes to model
circles, rectangles, and triangles.
• These classes have many common features
• What is the best way to design these classes so
– as to avoid redundancy and
– make the system easy to comprehend and
– easy to maintain?
• The answer is to use inheritance.
Superclasses and Subclasses
• Inheritance enables you to define a general
class (e.g., a superclass) and later extend it to
more specialized classes (e.g., subclasses).
• Whenever you inherit/extend a class, a copy
of superclass’s members is created in the
subclass object and thus, using the subclass
object you can access the members of both
classes.
Example
In the following example we have a class named SuperClass with a method with name
demo(). We are extending this class with another class (SubClass).
Now, you create an object of the subclass and call the method demo().

class SuperClass{
public void demo() {
System.out.println("demo method");
}
}
public class SubClass extends SuperClass {
public static void main(String args[]) {
SubClass obj = new SubClass();
obj.demo();
}
}
Output :
demo method
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
• The sum of the given numbers:30
• The difference between the given numbers:10
• The product of the given numbers:200
• Create three inherited classes named-
Crockery, Household, Food-items from
Product super class and inherit the instance
method( display() and setdata() ) and
variables(MRP and QUANTITY) of super class
Product
import java.util.*;
class product
{
int Mrp=0;
int Quantity=0;
void setdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter Mrp and quantity of products");
System.out.print("Enter Mrp:");
Mrp=sc.nextInt();
System.out.print("Enter Quantity:");
Quantity=sc.nextInt();
}
void display()
{
System.out.println("Mrp and quantity of products");
System.out.println("Mrp of the product is:"+Mrp);
System.out.println("Quantity of the product is:"+Quantity);
System.out.println():
}
}
class Household extends product
{
Household()
{
System.out.println("Household-item is added to the market");
}
}
class Crockery extends product
{
Crockery()
{
System.out.println("Crockery is added to the market");
}
}
class Food extends product
{
Food()
{
System.out.println("Food is added to the market");
}
}
class fifth_a
{
public static void main(String[] args)
{
Crockery c1=new Crockery();
c1.setdata();
c1.display();
Household h1=new Household();
h1.setdata();
h1.display();
Food f1=new Food();
f1.setdata();
f1.display();
}
}
• Create two inherited classes named-
Savings,Current from Account super class and
inherit the instance method(display (),setdata
() and deposit()) and variables(Ac_No,Name
and Balance) of super class Account.
public void display()
package bank; {
System.out.println("==========================");
import java.util.Scanner; System.out.println("Account number is:"+Ac_No);
class Account System.out.println("Account name is:"+Name);
{ System.out.println("Account balance is:"+Balance);
private int Ac_No; System.out.println("==========================");
}
private String Name;
public void deposit()
private int Balance;
{
public void setData() Scanner sc=new Scanner(System.in);
{ System.out.println("Enter the value you want to
Scanner sc=new Scanner(System.in); deposit...");
System.out.println("Enter Ac_No..."); int rs=sc.nextInt();
Ac_No=sc.nextInt();; Balance=Balance+rs;
System.out.println("Value Deposited Successfully...");
System.out.println("Enter Name...");
}
Name=sc.next(); }
System.out.println("Enter
Balance...");
Balance=sc.nextInt();
}
package bank;
import bank.*;
class Savings extends Account
{
public void Type()
{
System.out.println("Savings Account");
}
}
class Current extends Account
{
public void Type()
{
System.out.println("Current Account");
}
}
public class Customer3
{
public static void main(String []args)
{
Savings a1=new Savings();
a1.Type();
a1.setData();
a1.display();
Current a2=new Current();
a2.Type();
a2.setData();
a2.display();
}
}
As sub class not inherit
constructor from super class
How to call constructor of super class from
sub class??

Super
Keyword
Use of Super Keyword

Call
Constructor of Call Method
super class of super class
• The syntax to call a superclass’s constructor is:
• super(), or super(parameters);

• The statement super() invokes the no-arg


constructor of its superclass, and the statement
super(arguments) invokes the superclass
constructor that matches the arguments.
• The statement super() or super(arguments) must
appear in the first line of the subclass’s constructor
Must be 1st
statement
Constructors in cuboid class
• Cuboid (int l, int w, int h) {
Super(l,w);
Height = h;
}

Cuboid(int l){
this(l,l,l);
}
• Writing only super() will give compilation error because
super class does not contain no argument constructor
The super keyword
• It is used to differentiate the members of
superclass from the members of subclass, if
they have same names.
• It is used to invoke the superclass constructor
from subclass.
Method Overriding

From Super class

Inherit Override
Method Method
Method Overriding and use of super keyword

What is Method Overriding

Sub class defines method with same name and


signature as super class
Overriding
class Animal {
public void move() {
System.out.println("Animals can move"); Output
} Animals can move
} Dogs can walk and run

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
• What to do to call super class overridden
method from subclass?
class Animal {
public void move() {
System.out.println("Animals can move");
}
Output
}
Animals can move
Dogs can walk and run
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Call
Method
of super
class
• Return type : should be same( upto java 1.4)
• Then return type should be same or subtype
in overriding method
• Static methods are not inherited by sub- class
• When we have static method in the sub-class
that uses the same name and method
signature as the method in the super-class,
then it is known as method hiding and not
method overriding
• Because inheritance is about the behavior of
instances of a class, static methods and
variables are never inherited
• Create two inherited classes named-BE,ME from
Student super class and inherit the instance
method(display () and setdata ()) and
variables(Enrollment no and Name) of super class
Student and make an instance variable Entry_year
and final variable duration for each of the above class
• Super class will set the data of super class variable
and subclass will call the superclass methods and also
its own method set instance variables of same class
import java.util.Scanner;
class Student
{
private static int Er_No;
private String Name;
public void setData()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Enrollment No...");
Er_No=sc.nextInt();;
System.out.println("Enter Name...");
Name=sc.next();
}
public void display()
{
System.out.println("==========================");
System.out.println("Enrollment number is:"+Er_No);
System.out.println("Name is:"+Name);
}
}
package Syst;
import Syst.*;
import java.util.Scanner;
class BE extends Student
{
private int entry;
final int duration=4;
public void setData()
{
super.setData();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Entry Year....");
entry=sc.nextInt();
}
public void display()
{
super.display();
System.out.println("Entry year is :"+entry);
System.out.println("Duration is :"+duration+" years");
}
}
class ME extends Student
{
private int entry;
final int duration=2;
public void setData()
{
super.setData();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Entry Year....");
entry=sc.nextInt();
}
public void display()
{
super.display();
System.out.println("Entry year is :"+entry);
System.out.println("Duration is :"+duration+" years");
}
}
public class Person2
{
public static void main(String []args)
{
BE a1=new BE();
a1.setData();
a1.display();

ME a2=new ME();
a2.setData();
a2.display();
}
}
Variable shadowing

Sub class variable


which has same
name as super

How many
variables??
• How many instance variable in above
example?
• Ans – 3 (length and width from super class and
length of subclass)
• Length in cuboid is known as shadow variable
How to call variable with same name??

Solution

super
keyword
30*20=600 10*20=200
Find output
class Rectangle { class Cuboid extends Rectangle{
int length; int length ; // shadow variable
int width; //remains zero since it is not initialized
int area() { from constructor
return length*width;
}
int height;
void setDimensions(int l, int w) {
int volume() {
length = l;
return super.area() *height;
width = w;
}
void setDimensions(int l) { }
setDimensions( l, l);
} Cuboid(int l, int w, int h){
Rectangle (int l, int w){ super(l,w);
setDimensions(l,w); height = h;
} }
Rectangle(int l){
Cuboid(int l){
this(l,l);
this(l,l,l);
}
}
}
int area(){ // overriding method
return super.length *height;
}
class TestCuboid{
public static void main(String args[]) {
Rectangle r1,r2;
Cuboid c1,c2;

r1= new Rectangle(7,5);


r2= new Cuboid(7,5,4);
c1 = new Cuboid(7,5,4);

System.out.println("area of r1 is : " + r1.area()); // area() of rectangle -


System.out.println("area of r2 is : " + r2.area()); // area () of cuboid -
System.out.println("area of c1 is : " + c1.area()); // area() of cuboid -

System.out.println("length of r1 is : " + r1.length); //


System.out.println("length of r2 is : " + r2.length); //
System.out.println("length of c1 is : " + c1.length); //

}
}
class TestCuboid{
public static void main(String args[]) {
Rectangle r1,r2;
Cuboid c1,c2;

r1= new Rectangle(7,5);


r2= new Cuboid(7,5,4);
c1 = new Cuboid(7,5,4);

System.out.println("area of r1 is : " + r1.area()); // area() of rectangle - 35


System.out.println("area of r2 is : " + r2.area()); // area () of cuboid -28
System.out.println("area of c1 is : " + c1.area()); // area() of cuboid - 28

System.out.println("length of r1 is : " + r1.length); //7


System.out.println("length of r2 is : " + r2.length); //7
System.out.println("length of c1 is : " + c1.length); //0

}
}
• TestCuboid.java
Why?
• System.out.println("area of r2 is : " +
r2.area()); // area () of cuboid is called?
in java method binding is done at the runtime
So the method invocation is determined at the
runtime by the instance in which a method is
being invoked.
Since r2 refers to an instance of Cuboid the
method used will be of cuboid
Find Output
class Super {
int x;
Super(int x) {
class Temp {
this.x=x; public static void main(String[] args)
} {
void display() { Sub s1=new Sub(1,2);
System.out.println("Super x s1.display();
="+x);
}
}
}
}
class Sub extends Super {
int y;
Sub(int x, int y) {
super(x);
this.y=y;
}
void display() {
System.out.println("Sub x
="+x);
System.out.println("Sub y
="+y);
}
Using final with VARIABLES,METHODS
and CLASSES

Final
means
CONSTANT Can not be modified once
declared
Final with static variable

Can not modify

Can also initialize in


class Block

Can be initialized either at the place of declaration or in a static block

Static – one copy


Final – not modified
Final with instance variable

Can be initialized either at the place of declaration or in initializer block


or in the constructor

Exa : Rectangle class = color code for each rectangle is final


Final with Parameter Variable

Can be initialized by the invoker of the method or the constructor


They are not allowed to be modified in the method
Final with local variable

Can not modify


Final with Method

Prevent Override
Final with class

Prevent Inheritance
Types of inheritance
• Java supports the following four types of
inheritance:
• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance

• a sub-class is derived from only one super


class.
• It inherits the properties and behavior of a
single-parent class. Sometimes it is also known
as simple inheritance.
Multi-level Inheritance
• a class is derived from a class which is also
derived from another class
• a class that has more than one parent class is
called multi-level inheritance.
• Note that the classes must be at different
levels. Hence, there exists a single base class
and single derived class but multiple
intermediate base classes.
Hierarchical Inheritance
• If a number of classes are derived from a
single base class, it is called hierarchical
inheritance.
Hybrid Inheritance
TEST
public class test
{
public static void main (String[] args)
{
float f1 = -75;
float f2 = 0;
System.out.println(f1/f2);
}
}
• Compilation error
• Runtime error inline 5
• Infinity
• -Infinity
• NaN
• None of above
Rules for Method Overriding
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overriding method in the
sub class cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared public
or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
• Constructors cannot be overridden.
Casting objects and instanceof operator
• One object reference can be typecast into
another object reference. This is called casting
object.
• Object o = new Student(); // Implicit casting
– is legal because an instance of Student is an
instance of Object.

– Implicit casting = Upcasting/widening


Implicit casting :Upcasting/widening
• It is always possible to cast an instance of a
subclass to a variable of a superclass (known
as upcasting),
– because an instance of a subclass is always an
instance of its superclass.
– Widening
explicit casting :downcasting/ Narrowing
…..
• when casting an instance of a superclass to a
variable of its subclass (known as downcasting),
explicit casting must be used to confirm your
intention to the compiler with the
– (SubclassName) cast notation.
– Narrowing
– It requires explicit casting, it is allowed at compile
time, it is not always safe and may result in runtime
Exceptions.
example
• Student b = o; // o is object of object class
• In this case a compile error would occur.
• Why does the statement Object o = new Student()
work but Student b = o doesn’t?
• The reason is that a Student object is always an
instance of Object, but an Object is not necessarily
an instance of Student.
• Even though you can see that o is really a Student
object, the compiler is not clever enough to know
it.
explicit casting
• To tell the compiler that o is a Student object,
use explicit casting.
• The syntax is similar to the one used for
casting among primitive data types.
• Enclose the target object type in parentheses
and place it before the object to be cast, as
follows:
• Student b = (Student)o; // Explicit casting
instanceof operator
• For the casting to be successful, make sure that the object
to be cast is an instance of the subclass.
• If the superclass object is not an instance of the subclass,
a runtime ClassCastException occurs.
• For example, if an object is not an instance of Student, it
cannot be cast into a variable of Student.
• It is a good practice, therefore, to ensure that the object
is an instance of another object before attempting a
casting.
• This can be accomplished by using the instanceof
operator.
instanceof
• In Java, instanceof operator is used to check
the type of an object at runtime.
• instanceof operator return boolean value, if
an object reference is of specified type then it
return true otherwise false.
Object myObject = new Circle();
... // Some lines of code

/** Perform casting if myObject is an instance of Circle */


if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
• Why not define myObject as a Circle type in
the first place? To enable generic
programming,
• it is a good practice to define a variable with a
supertype, which can accept a value of any
subtype.
note
• instanceof is a Java keyword.
• Every letter in a Java keyword is in lowercase.
analogy
• To help understand casting, you may also consider
the analogy of fruit, apple, and orange, with the
Fruit class as the superclass for Apple and
Orange.
• An apple is a fruit, so you can always safely assign
an instance of Apple to a variable for Fruit.
• However, a fruit is not necessarily an apple, so
you have to use explicit casting to assign an
instance of Fruit to a variable of Apple.
Example:
class Student {..} //super class
class Undergraduate extends student{..}//subclass
class Graduate extends Student{..}//subclass

// instances
Student student1, student2;
student1 =new UnderGraduate();//widening,valid
student2 =new Graduate();//widening,valid

Graduate student3;
student3 = student2;//compilation error
student3 = (Graduate)student2;//explicit cast //done,valid
• public class Test {
• public static void main(String[] args)
• {
Test t= new Test();
System.out.println(t instanceof Test); }
}

• true
Find output : Example
class Parent{}
class Child1 extends Parent{}
class Child2 extends Parent{}
class Test { public static void main(String[] args) {
Parent p =new Parent();
Child1 c1 = new Child1();
Child2 c2 = new Child2();
System.out.println(c1 instanceof Parent); //true
System.out.println(c2 instanceof Parent); //true
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //false

p = c1;
System.out.println(p instanceof Child1); //true
System.out.println(p instanceof Child2); //false

p = c2;
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //true
}}
Other operators
• New : create new instance
• [] : access the elements of an arrary
• . : access any member of an instance or
invoking methods on an instance
Thank you

You might also like