Inheritance
Inheritance - basics
• Inheritance is the process by which one object
acquires the properties of another object.
• This is important because it supports the concept
of hierarchical classification.
• In java terminology,
– a class that is inherited is called a super class
– The class that does the inheriting is called a subclass.
– Use the extends keyword.
• Using super class object, we can access the
members of super class
• Using sub class object, we can access both
super class and sub class members.
• We cannot directly assign super class
reference value to sub class object
– ClassCastException
• We can directly assign sub class reference
value to super class object.
– But we can access the fields and methods of super
class.
//Example:But we can access only the fields and methods of super class.
class Super
{ int x=10;
int y=20;
}
class Derived extends Super
{ int z=30;}
class InheritanceExample1
{
public static void main(String args[])
{
Super s=new Derived();
System.out.println("X="+s.x);
System.out.println(“Y="+s.y);
System.out.println(“Z="+s.z);
}
}
D:\javalab2017\Inheritance>javac InheritanceExample1.java
InheritanceExample1.java:17: error: cannot find symbol
System.out.println(“Z="+s.z);
^
symbol: variable z
location: variable s of type Super
1 error
class Super
{ int x=10; D:\javalab2017\Inheritance>javac
int y=20; InheritanceExample1.java
int z=40;} InheritanceExample1.java:23: error: cannot
class Derived extends Super find symbol
{ s.fnDerived();
int z=30; ^
void fnDerived() symbol: method fnDerived()
{ System.out.println("fnDerived");}
location: variable s of type Super
} 1 error
class InheritanceExample1
{
public static void main(String args[])
{
Super s=new Derived();
System.out.println("X="+s.x);
System.out.println("Y="+s.y);
System.out.println("Z="+s.z);
s.fnDerived();
}
Dynamic Method Dispatch(Run time polymorphism)
Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
// Dynamic Method Dispatch
class Dispatch {
class A { public static void main(String args[]) {
void callme() A a = new A(); // object of type A
{ System.out.println("Inside A's callme B b = new B(); // object of type B
method"); } C c = new C(); // object of type C
} A r; // obtain a reference of type A
class B extends A { r = a; // r refers to an A object
void callme() r.callme(); // calls A's version of callme
{ System.out.println("Inside B's callme r = b; // r refers to a B object
method"); r.callme(); // calls B's version of callme
} r = c; // r refers to a C object
} r.callme(); // calls C's version of callme
}
class C extends A {
}
void callme()
Output:
{ System.out.println("Inside C's callme
D:\java2016\program\Inheritance>java Dispatch
method");
Inside A's callme method
} } Inside B's callme method
class Super D:\javalab2017\Inheritance>javac
{ InheritanceExample1.java
int x=10;
int y=20;
int z=40;
D:\javalab2017\Inheritance>java
} InheritanceExample1
class Derived extends Super X=10
{ Y=20
int z=30; Z=40
}
class InheritanceExample1
{ //derived class data member cant
public static void main(String args[])
{
be accessed by using super class
Super s=new Derived(); reference
System.out.println("X="+s.x);
System.out.println("Y="+s.y);
System.out.println("Z="+s.z);
}
class SuperStatic
{
static void staticMethod()
D:\javalab2017\Inheritance>java
{ StaticExample
System.out.println("Superclass static method"); Superclass static method
}
} Superclass static method
class DerivedStatic extends SuperStatic Derivedclass static method
{ static void staticMethod()
{
Derivedclass static method
System.out.println("Derivedclass static method");
}
//we can call static method by using
}
class StaticExample classname and also by using
{ object
public static void main(String args[]) //In run time polymorphism or
{SuperStatic obj=new DerivedStatic();
DerivedStatic obj1=new DerivedStatic();
dynamic method dispatch->base
obj.staticMethod(); class static method is called
SuperStatic.staticMethod(); Because the static method can’t be
obj1.staticMethod();
override
DerivedStatic.staticMethod();
}
class Base{ D:\javalab2017\Inheritance>javac Derived1.java
Base()
{ D:\javalab2017\Inheritance>java Derived1
System.out.println("Base"); Base
} derived obj created Derived constructor
Base(String str)
From Main
{
System.out.println(str+" Base constructor");}
}
class Derived1 extends Base
{
Derived1(String str)
{
System.out.println(str+" Derived constructor");
}
public static void main(String args[])
{
Base obj=new Derived1("derived obj created");
System.out.println("From Main");
}
}
class Base{
Base()
{
System.out.println("Base");
}
Base(String str) D:\javalab2017\
{
Inheritance>java Derived1
System.out.println(str+" Base constructor");}
} derived obj created Base
class Derived1 extends Base constructor
{
Derived1(String str) derived obj created Derived
{ constructor
super(str);
System.out.println(str+" Derived constructor"); From Main
}
public static void main(String args[])
{
Base obj=new Derived1("derived obj created");
System.out.println("From Main");
}
• Super keyword
– Whenever a subclass needs to refer to its immediate super class, it can do
so by use of the keyword super
• calls the super class’ constructor
super (parameter-list);
• access a member of the super class that has been hidden by a member of a subclass
– super( ) must always be the first statement executed inside a subclass’ constructor
Example
class Base1
{ int x=10; }
class Derived1 extends Base1
{ int x=15;
void disp()
{System.out.println(super.x);
System.out.println(x);
}
public static void main(String args[])
{ Derived1 obj=new Derived1();
obj.disp();
}
}
Output
D:\java2016\program\Inheritance>java Derived1
10
Introducing access control
• Accessibility modifiers or access specifiers
– can control what parts of a program can access the members of a
class
– a class can control what information is accessible to clients
– allowing access to data only through a well-defined set of methods
thereby prevent misuse.
• public
– member can be accessed by any other code
– least restrictive of all the accessibility modifiers
– accessible from anywhere, both in the package containing its class and in other packages
where this class is visible
• private
– member can only be accessed by members of its class
• default (also called package accessibility)
– the member is only accessible by other classes in its own class’s package.
– Even if its class is visible in another package, the member is not accessible elsewhere.
• Protected
– accessible in all classes in the same package, and by all subclasses of its class in
any package where this class is visible
– Non subclasses in other packages cannot access protected members from other
packages.
class Base{
Base(String str) • Without super(str) statement in derived
{ System.out.println(str+" Base constructor");} class constructor ,the program will show
} error.
class Derived extends Base • By default - from the derived class
{Derived(String str) parameterized constructor(from all
{ //super(str); constructor) the base class no argument
System.out.println(str+" Derived constructor");} constructor will be call .
public static void main(String args[]){ • But there is no noargument constructor in
Derived obj=new Derived("derived obj created"); Base class
System.out.println(" From Main");} • Hence we need to explicitly call the Base class
parameterized constructor by using
}
super( parameter-list).
Output:
• To explicitly call the Base class no argument
D:\java2016\program\Inheritance>javac Derived.java
constructor - super( ) is used.
Derived.java:11: error: constructor Base in class Base
• This super() should be the first statement of
cannot be applied to give n types;
the constructor.
{
• Because, before instantiated the derived class
^
member the base class member must be
required: String instantiated.
found: no arguments With super(str) the following output will get
reason: actual and formal argument lists differ in Output:
length D:\java2016\program\Inheritance>java Derived
1 error derived obj created Base constructor
derived obj created Derived constructor
Abstract Classes
• abstract methods are sometimes referred to as subclasser responsibility
because they have no implementation specified in the superclass.
• Thus, a subclass must override them—it cannot simply use the version
defined in the superclass.
abstract method, use this general form:
abstract type name(parameter-list);
• no method body is present.
• Any class that contains one or more abstract methods must also be
declared abstract.
• There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Also, you cannot
declare abstract constructors, or abstract static methods.
because constructor and static method can’t be override , hence run time
polymorphism not possible for static method(it will always call the base
class method)
• Any subclass of an abstract class must either implement all of the abstract
methods in the superclass, or be declared abstract itself.
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A
{ void callme()
{ System.out.println("B's implementation of callme."); }
}
class AbstractDemo
{ public static void main(String args[])
{ B b = new B();
b.callme();
b.callmetoo();
}
}
Output:
D:\java2016\program\Inheritance>java AbstractDemo
B's implementation of callme.
Final
• Methods declared as final cannot be overridden.
• The compiler is free to inline calls to them because it “knows” they will
not be overridden by a subclass.
• However, since final methods cannot be overridden, a call to one can be
resolved at compile time. This is called early binding.
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!");
}
}
• Using final to Prevent Inheritance
• Declaring a class as final implicitly declares all of its methods as
final, too.
• As you might expect, it is illegal to declare a class as both abstract
and final since an abstract class is incomplete by itself and relies
upon its subclasses to provide complete implementations.
• Here is an example of a final class:
• final class A { //... }
// The following class is illegal.
class B extends A
{ // ERROR! Can't subclass A //... }
The Object Class
• There is one special class, Object is a super class of all other classes. This means
that a reference variable of type Object can refer to an object of any other class.
import java.util.*;
class Account
{
protected int accnumber;
protected double balance;
public Account( )
{ accnumber=0;
balance=0.0;
}
public Account( int accnumber,double balance)
{ this.accnumber=accnumber;
this.balance=balance;
}
}
class SBAccount extends Account
{ public SBAccount( )
{ super( ); }
public SBAccount(int accno,double init_bal)
{ super(accno,init_bal); }
public void deposit(double amt)
{ if(amt > 0)
{ balance= balance + amt;
System.out.println("customeraccnumber:"+accnumber);
System.out.println("customer balance:"+balance);
}
else
{ System.out.println(" IllegalArgumentException"); }
}
public void withdraw(double amt)
{ if( super.balance - amt >1000)
{ balance = balance - amt;
System.out.println("customeraccnumber:"+accnumber);
System.out.println("customer balance:"+balance);
}
else
{ System.out.println("InsufficientFundsException"); }
}
public void calc_interest( )
{ balance = balance + ((0.04*balance));
System.out.println("customeraccnumber:"+accnumber);
System.out.println("customer balance:"+balance);
class FDAccount extends Account
{ int period;
public FDAccount( )
{ super( );
this.period = 0;
}
public FDAccount(int accno,double init_bal,int period)
{ super( accno,init_bal);
this.period = period;
}
double calc_interest( )
{ return ((period*0.0825*balance)); }
public void close( )
{ balance = balance + calc_interest();
System.out.println("customeraccnumber:"+accnumber);
System.out.println("customer balance:"+balance);
}
}
class Customer public void createAccount(int type)
{
{ int cust_id; Scanner sc=new Scanner(System.in);
String name,adress; System.out.println("Enter the Accno");
SBAccount SB; int accno=sc.nextInt();
System.out.println("Enter the initial balance");
FDAccount FD; double init_bal=sc.nextDouble();
public Customer( )
{ this.cust_id= 0; if(type==1)
{
SB= new SBAccount(accno,init_bal );
this.name="Unknown"; }
else
this.adress="Unknown"; {
System.out.println("enter the period");
}
int period=sc.nextInt();
public Customer(int id,String FD=new FDAccount(accno,init_bal,period);
name,String adress) }
{ this.cust_id= id; }
this.name= name; void display()
this.adress= adress; {
System.out.println("ID:"+cust_id);
} System.out.println("Name:"+name);
System.out.println("Address:"+adress);
}
public void transaction(int transtype)
{
Scanner sc=new Scanner(System.in);
if(transtype == 1)
{ if(SB!=null)
{System.out.println("Enter the deposit amount");
int depo=sc.nextInt();
display();
SB.deposit(depo);
}
else
System.out.println("This customer does not have SB account");
}
else if(transtype == 2)
{ if(SB!=null)
{
System.out.println("Enter the withdraw amount");
int with=sc.nextInt();
display();
SB.withdraw(with);
}
else
System.out.println("This customer does not have SB account");
}
else if(transtype == 3)
{
if(SB!=null)
{
display();
SB.calc_interest( );
}
else
System.out.println("This customer does not have SB account");
}
else if(transtype == 4)
{ if(FD!=null)
{
display();
FD.close( );
}
else
System.out.println("This customer does not have FD account");
}
else
System.out.println("Invalid transaction type");
}
}
class InheritanceProgram
do
{ public static void main(String args[])
{
{ Scanner sc=new Scanner(System.in); System.out.println("Enter the customer id");
int choice; int i= sc.nextInt();
Customer[ ] C= new Customer[3]; if(i>=0 &&i<=2)
for ( int i = 0; i <C.length; i++) {
System.out.println("Enter the transaction type");
{
System.out.println("Enter System.out.println("1.deposit2.withdraw3.SB_calc_i
customer name"); nterest4.FDclose");
String
name=sc.nextLine(); int j= sc.nextInt();
C[i].transaction(j);
System.out.println("Enter
customer address");
}
String else
adress=sc.nextLine(); System.out.println("Enter the currect customer id");
C[i]= new Customer(i,name,adress); System.out.println("Do you want to continue? Enter 1");
System.out.println("Enter choice=sc.nextInt();
the account type (1)SB (any value) FD"); char ch=sc.nextChar();
int type=sc.nextInt(); }while(choice==1);
}
C[i].createAccount(type);
}
sc.nextLine();
}