Sie sind auf Seite 1von 28

Inheritance

Objective
Inheritance Multilevel Hierarchy Constructor calling sequence Subclass Object assignment to super class reference Super keyword Method Overriding Dynamic method dispatch Abstract Classes Using final Object class

Inheritance
When a class B acquires the properties of another class A, then class B is said to have inherited class A. Here, class A is a superclass and class B is a subclass. A subclass inherits all the instance variables and methods defined by the superclass and adds its own, unique elements. The keyword extends is used to inherit a class. Eg: class subclass extends superclass {

Inheritance
Every class in Java is an extended class, whether it is declared with an extends keyword or not. If a class does not explicitly extend from another class, it implicitly extends the Object class.

Example: Inheritance
public class BankAccount { int acctNum; String name; public BankAccount(int bAcctNum, String name) { acctNum = bAcctNum; . } public double getBalance () { } }

Example: Inheritance
public class CheckingAccount extends BankAccount { double interest; public CheckingAccount(int aNum, String aName, double aInt) { super (aNum, aName); interest = aInt; } public double calculateInterest() { . }}

MultiLevel Inheritance
class A{ int a=1; int b=2; void dispa(){ System.out.println( a+b);} } class B extends A{ int c=3; void dispb() { System.out.println(a+b+c);} } class C extends B{ int d=4; void dispc() {System.out.println(a+b+c+d);} } class M { public static void main(String args[]){ A a=new A(); B b=new B(); C c=new C(); a.dispa(); b.dispb(); c.dispc(); }

Constructor call sequence


Constructors in a class hierarchy are called in the order of derivation. In previous example ,while creating object of B class ,the default constructor of the A class is called and then Bs constructor is called.

Assigning super class reference to subclass Object


class T { int t; void disp() {System.out.println(t);} class D extends T{ int d; void disp() { System.out.println(d);} void add() {} } class TestRef{ public static void main(String s[]) { T tref; D dref =new D(); tref=dref; //but not vice versa tref.t =9; tref.disp() ; // no problem //but with tref you cannot access the additional members of derived class though it is refering to derived class object. //common functions always chosen from derived i.e disp() of D is called in above disp call } }

super
Basically super is used to refer to base class from any derived class Whenever a subclass extends class super(), it is calling the constructor of its immediate superclass. super() must be the first statement executed inside a subclass constructor. super.member always uses the superclasss member (member could be a method or an instance variable)

Base class instance hiding


class A{ int a=10; } o/p: class B extends A{ 29 29 int a=29; void disp(){ System.out.println(a+\t+a);} public static void main(String arg[]) { B b=new B(); To refer a of base b.display(); Use super.a }}

Calling constructor through super


class A { int b; A( ) {b=10;} A(int k) {b=k;} } class B extends A {int g; B( ) { super(9); g=90;} public static void main(String args[]) { B bref=new B( ); System.out.println(bref.b+\t+bref.g); }

Method Overriding
When a method in a subclass has the same name and type signature as that of a method in its superclass, then the method in the subclass is said to override the method in the superclass. Only non-static methods can be overridden. Both signature and return type must be the same as the superclass.

Example: Method Overriding


public class Parent { public void hello() { System.out.println(Hello from parent); } } public class Child extends Parent { public void hello() { System.out.println(Hello from Child); } }

Method Overriding
An extended class can change the access of a superclasss methods, but only if it provides more access. A method declared private in the super class can be redeclared protected or public, in the derived. i.e you can enhance access not prohibit with respect to base class Fields cannot be overridden; they can only be hidden. To access the hidden fields use the super keyword. [This is another case of instance variable hiding]

Dynamic method dispatch


Methods for execution are selected based on run time assignment of object to the reference and not based on object type. Call to a overriden method is resolved during run time,rather than compile time. Type of object being refered to and not the type of the reference variable.

An Example
public class BankAccount { protected double getBalance() { return 1000.00; } } public class SavingsAccount extends BankAccount{ protected double getBalance() { return 1010.00; }

An Example
protected void printBalance() { BankAccount ba = this; //superclass variable //can reference //subclass object. System.out.println(super.getBalance()); System.out.println(this.getBalance()); System.out.println(ba.getBalance()); } }

final and Inheritance


A method declared final cannot be overridden A class can also be declared final. Such a class cannot be extended.
final class Security { // }

A final classs methods are implicitly final.

Abstract Classes
A superclass that only defines a generalized form that will be shared by all its subclasses, leaving the implementation details to its subclasses is said to be an abstract class. A concrete class has concrete methods, including implementations of any abstract methods inherited from its superclasses. [A class which is non abstract] Any class with abstract methods should be declared abstract. Cannot declare static and private member methods as abstract.

Example: Abstract Class


abstract class Shape { abstract double area(); public void display () { // Do something } // concrete method

}
class Square extends Shape { double area() { // Do something }

Abstract Classes
An abstract class cannot have objects because it is not complete, but it can have references. Static methods and constructors cannot be declared abstract. Any subclass of an abstract class must either implement all the abstract methods in the superclass or be itself declared abstract. A concrete method can be overriden to become abstract. It is illegal to declare a class both final and abstract.

Example For an abstract class


Shape

rectangle

square

triangle

Object : defines the following methods, which means that they are available in every objec t. Method P urpose Object clone( ) Creates a new object that is the same as the object b eing cloned. boolean equals(Object object) D etermines whether one object is equal to another. void finalize( ) C alled before an unused object is recycled.

Class getClass( ) O btains the class of an object at run time. int hashCode( ) Returns the hash code associated with the invoking o bject. void notify( ) Resumes execution of a thread waiting on the invoking

void notifyAll( )

Resumes execution of all threads waiting on the i nvoking object. R eturns a string describes

String toString( ) that the object. void wait() void

wait(long milliseconds) void wait(long milliseconds, int nanoseconds)

W aits on another thread of execution. The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.

The equals( ) method compares the contents of two objects. It returns true if the objects are equivalent, and false otherwise. The toString( ) method returns a string that contains a description of the object on which it is called. Also, this method is automatically called when an object is output using println( ).

Das könnte Ihnen auch gefallen