Anda di halaman 1dari 65

BITS Pilani

BITS Pilani
Hyderabad Campus

Dr.Aruna Malapati Asst Professor Department of CSIS

BITS Pilani
Hyderabad Campus

OBJECT ORIENTED PROGRAMMING Inheritance

Todays Agenda
Objective: derive a new class from existing class Recognize the path of inheritance of classes in JDK Inherence model is the "is-a-relationship", not a "hasrelationship" All of the classes you use or define are implicitly inherited from the top class, Object

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

INHERITANCE BASICS
1. Reusability is achieved by INHERITANCE

2. Java classes Can be Reused by extending a class. Extending an existing class is nothing but reusing properties of the existing classes.
3. The class whose properties are extended is known as

super or base or parent class.


4. The class which extends the properties of super class is

known as sub

or derived or child class

5. A class can either extends another class or can implement an interface


CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Objects are instances of a given class

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Inheritance

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Creating a subclass
Creating a subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override the methods of the superclass

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A {..} class B extends A { .. }

<<class>>

A super class
B sub class class B implements A { .. } A interface B sub class
B A

<<class>>

<<interface>>

<<class>>

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Various Forms of Inheritance


Single Inheritance A A Hierarchical Inheritance X X

MultiLevel Inheritance A B A

NOT SUPPORTED BY JAVA Multiple Inheritance A B SUPPORTED BY JAVA A B

B
C
CS/IS F213 First Semester 2012-13

C
BITS Pilani, Hyderabad Campus

Forms of Inheritance
Multiple Inheritance can be implemented by implementing multiple interfaces not by extending multiple classes Example :
A class Z extends A implements C , D C D

{ }

OK
class Z extends A ,B {

class Z extends A extends B {

OR
}

WRONG

}
CS/IS F213 First Semester 2012-13

WRONG
BITS Pilani, Hyderabad Campus

Defining a Subclass
Syntax :

class <subclass name> extends <superclass name>


{ variable declarations;

method declarations;
}

Extends keyword signifies that properties of the super class are extended to sub class
Sub class will not inherit private members of super class
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Inheritance Basics
1. Whenever a sub class object is created ,super class constructor is called first. 2. If super class does not have any constructor of its own OR has an unparametrized constructor then it is automatically called by Java Run Time by using call super() 3. If a super class has a parameterized constructor then it is the responsibility of the sub class constructor to call the super class constructor by call super(<parameters required by super class>) 4. Call to super class constructor must be the first statement in sub class constructor
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Inheritance Basics
When super class has a Unparametrized constructor
class A { A() { System.out.println("This is constructor of class A"); } } // End of class A class B extends A { B() { super(); System.out.println("This is constructor of class B"); } } // End of class B
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class inhtest { public static void main(String args[]) { B b1 = new B(); } } OUTPUT This is constructor of class A This is constructor of class B

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { A() { System.out.println("This is class A"); } } class B extends A { B() { System.out.println("This is class B"); } } class inherit1 { public static void main(String args[]) { B b1 = new B(); } }
CS/IS F213 First Semester 2012-13

/* E:\Java>java inherit1 This is class A This is class B E:\Java> */

BITS Pilani, Hyderabad Campus

class A { private A() { System.out.println("This is class A"); } } class B extends A /* { E:\Java>javac xyz1.java B() xyz1.java:12: A() has private access in { A System.out.println("This is class B"); { } ^ } 1 error class inherit2 */ { public static void main(String args[]) { B b1 = new B(); } } CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class A { private A() { System.out.println("This is class A"); } A() { System.out.println("This is class A"); } /* } E:\Java>javac xyz2.java class B extends A { xyz2.java:7: A() is already defined in A B() A() { ^ System.out.println("This is class B"); xyz2.java:16: A() has private access in A } { } ^ class inherit2 2 errors { */ public static void main(String args[]) { B b1 = new B(); }} CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Note:
Private members are not accessible outside the class. If a constructor is made private, then the object also needs to be created within the class. Private constructor cannot be accessed from an inherited class.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

When Super class has a parametrized constructor


class A { private int a; B b1 = new B(10,8.6); A( int a) { this.a =a; System.out.println("This is constructor of class A"); } }
class B extends A { private int b; private double c; B(int b, double c) { this.b=b; this.c=c; System.out.println("This is constructor of class B"); } }

D:\java\bin>javac inhtest.java inhtest.java:15: cannot find symbol symbol : constructor A() location: class A { ^ 1 errors
BITS Pilani, Hyderabad Campus

CS/IS F213 First Semester 2012-13

class A { private int a; A( int a) { this.a =a; System.out.println("This is constructor of class A"); }} class B extends A { B b1 = new B(8,10,8.6); private int b; private double c; B(int a,int b,double c) { OUTPUT super(a); This is constructor of class A this.b=b; This is constructor of class B this.c=c; System.out.println("This is constructor of class B"); }}
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class A { private int a; protected String name; A(int a, String n) { this.a = a; this.name = n; } void print() { System.out.println("a="+a); } }

a is private in class A Call to print() from super class A

class B extends A { int b; double c; B(int a,String n,int b,double c) { super(a,n); this.b=b; this.c =c; } void show() { //System.out.println("a="+a); print(); System.out.println("name="+name); System.out.println("b="+b); System.out.println("c="+c); } }

Accessing name field from super class (super.name)


CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class xyz3 { public static void main(String args[]) { B b1 = new B(10,"OOP",8,10.56); b1.show(); } } E:\Java>java xyz3 a=10 name=OOP b=8 c=10.56
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

USE OF super KEYWORD


Can be used to call super class constructor super(); super(<parameter-list>); Can refer to super class instance variables/Methods super.<super class instance variable/Method>

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { private int a; A( int a) { this.a =a; System.out.println("This is constructor of class A"); } void print() { System.out.println("a="+a); } void display() { System.out.println("hello This is Display in A"); } } // End of class A

class B extends A { private int b; private double c; B(int a,int b,double c) { super(a); this.b=b; this.c=c; System.out.println("This is constructor of class B"); } void show() { print(); System.out.println("b="+b); System.out.println("c="+c); } } // End of class B

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class inhtest1 { public static void main(String args[]) { B b1 = new B(10,8,4.5); b1.show(); } } /* OutPUt D:\java\bin>java inhtest1 This is constructor of class A This is constructor of class B a=10 b=8 c=4.5 */
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

A Superclass Variable can Reference a Subclass Object


A subclass object can be assigned to the superclass reference

Super class

Super ob

Sub class

Sub ob

RefDemo.java

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Multilevel Inheritance
You can build hierarchies that contain as layer of inheritance as you want. DemoMultiLevel.java

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Methods overriding
1. Sub class can override the methods defined by the super class. 2. Overridden Methods in the sub classes should have same name, same signature , same return type and may have either the same or higher scope than super class method. 3. Java implements Run Time Polymorphism/ Dynamic Method Dispatch by Method Overriding. [Late Binding] 4. Call to Overridden Methods is Resolved at Run Time. 5. Call to a overridden method is not decided by the type of reference variable Rather by the type of the object where reference variable is pointing. 6. While Overriding a Method, the sub class should assign either same or higher access level than super class method.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { void show() { System.out.println("Hello This is show() in A"); }// End of show() Method } // End of class A B class overrides show() class B extends A { method from super class A void show() { System.out.println("Hello This is show() in B"); }// End of show() Method } // End of class B class override { public static void main(String args[]) { Call to // super class reference variable show() of A // can point to sub class object class A a1 = new A(); a1.show(); Call to a1 = new B(); show() of B a1.show(); } class
CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Is this Method Overriding class A { NO void show(int a) { System.out.println("Hello This is show() class override1 in A"); { } public static void main(String args[]) } { class B extends A { A a1 = new A(); void show() a1.show(10); { System.out.println("Hello This is show() B b1 = new B(); in B"); b1.show(10); } b1.show(); } } OUTPUT
Hello This is show() in A Hello This is show() in A Hello This is show() in B Method overriding occurs only when the names and the type signatures of the two methods are identical.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Dynamic Method Dispatch


1. Super class reference variable can refer to a sub class object.
2. Super class variable if refers to sub class object can call only overridden methods. 3. Call to an overridden method is decided by the type of object referred to. A a1 = new B(); a1.show(); // call to show() of B a1 = new C(); a1.show(); // call to show() of C a1 = new D(); a1.show(); // call to show() of D
A

Assume show() Method is Overridden by sub classes


CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

DYNAMIC METHOD DISPATCH


class A { void show() { System.out.println("Hello This is show() in A"); } } class B extends A { void show() { System.out.println("Hello This is show() in B"); } } class C extends A { void show() { System.out.println("Hello This is show() in C"); } } class D extends A { void show() { System.out.println("Hello This is show() in D"); } } CONTINUED..
BITS Pilani, Hyderabad Campus

CS/IS F213 First Semester 2012-13

class override2 { public static void main(String args[]) { A a1 = new A(); a1.show(); a1 = new B(); a1.show(); a1 = new C(); a1.show(); a1 = new D(); a1.show(); } }

Hello This is show() in A Hello This is show() in B Hello This is show() in C

Hello This is show() in D

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class override3 { public static void main(String args[]) { A a1 = new B(); B b1 = (B) a1;
/* A a1 = new B(); C c1 = (C) a1; Exception in thread "main" java.lang.ClassCastException: B at override3.main(override3.java:39) */ } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Examples Overriding
class A { void show() { . } } class B extends A { void show() { . } void show(int x) { } void print() { } } A a1 = new B(); a1.show() ; // Valid // a1.show(10); // Invalid //a1.print(); // Invalid

When a super class variable points to a sub class object, then it can only call overridden methods of the sub class.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class A { protected void show() { System.out.println("Hi"); } } class B extends A { void show() { System.out.println("Hi"); } }

D:\Java1>javac AB.java AB.java:10: show() in B cannot override show() in A; attempting to assign weaker access privileges; was protected void show() ^ 1 error

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { private void show() { System.out.println("Hi"); } } class B extends A { int show() { System.out.println("Hi"); return 10; } }

IS THIS METHOD OVERRIDING

NO
CODE WILL COMPILE & RUN SUCESSFULLY

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { static int show() { System.out.println("class A"); return 0; } }

Whats Wrong Here

class B extends A { void show() { System.out.println("class B"); } }

sample.java:12: show() in B cannot override show() in A; overridden method is st atic void show() ^ 1 error
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Whats Wrong Here


class A { static int show() { System.out.println("class A"); return 0; } } class B extends A { static int show() { System.out.println("class B"); } }

Nothing
The code will compile and run successfully. Method Hiding B class Hides show() method from super class A

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Will code Compile Sucessfully


class A { static int show() { System.out.println("SHOW METHOD OF CLASS A"); return 0; }// End of show() Method TestAB.java:11: show() in B cannot override show() in A; }// End of class A attempting to use incompatible return type class B extends A found : void required: int static void show() { static void show() { System.out.println("SHOW METHOD OF CLASS B"); }// End of show() Method }// End of class B

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

class A { static int show() { System.out.println("SHOW METHOD OF CLASS A"); return 0; }// End of show() Method }// End of class A class B extends A { static int show() { System.out.println("SHOW METHOD OF CLASS B"); return 0; }// End of show() Method }// End of class B

class TestAB { public static void main(String args[]) { A a1 = new B(); System.out.println(a1.show()); B b1 = new B(); b1.show(); } }

E:\Java Programs>java TestAB SHOW METHOD OF CLASS A 0 SHOW METHOD OF CLASS B


BITS Pilani, Hyderabad Campus

CS/IS F213 First Semester 2012-13

class A { private int a; private int b; private int c; A() { a=b=c=10; } A(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int getA() { return this.a;} public int getB() { return this.b;} public int getC() { return this.c;} public void show() { System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); }// End of show() Method }// End of class A

class B extends A { private int d; B() { super(); d=10; } B(int a, int b, int c,int d) { super(a,b,c); this.d = d; } public int getD() { return this.d;} public void show() { System.out.println("a="+super.getA()); System.out.println("b="+super.getB()); System.out.println("c="+super.getC()); System.out.println("d="+this.d); }// End of show() Method }// End of class B
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

class Test { public static void main(String args[]) { A a1 = new B(); System.out.println(a1.getA()); System.out.println(a1.getD()); a1.show(); }// End of main() Method }// End of class Test

Test.java:56: cannot find symbol symbol : method getD() location: class A System.out.println(a1.getD());
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Final and Abstract Classes

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Restricting Inheritance

Parent
Inherited capability

Child

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Final Members: A way for Preventing Overriding of Members in Subclasses All methods and variables can be overridden by default in subclasses. This can be prevented by declaring them as final using the keyword final as a modifier. For example:
final int marks = 100; final void display();

This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Final Classes: A way for Preventing Classes being extended


We can prevent an inheritance of classes by other classes by declaring them as final classes. This is achieved in Java by using the keyword final as follows:
final class Marks { // members } final class Student extends Person { // members }

Any attempt to inherit these classes will cause an error. If a class is final, all its methods are also final.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
class PersonalLoan{ public final String getName(){ return "personal loan"; } } class CheapPersonalLoan extends PersonalLoan{ public final String getName(){ return "cheap personal loan"; //compilation error: overridden method is final } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

example of final class in java


Final class is complete in nature and can not be subclassed or inherited final class PersonalLoan{ } class CheapPersonalLoan extends PersonalLoan{ //compilation error: cannot inherit from final class }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Benefits of final keyword in Java


1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables. 2. Final variables are safe to share in multi-threading environment without additional synchronization overhead. 3. Final keyword allows JVM to optimized method, variable or class.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Final and Immutable Class in Java


Final keyword helps to write immutable class. Example of Final in Java Java has several system classes in JDK which are final, some example of final classes are String, Integer, Double and other wrapper classes.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Abstract Method & Class

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Abstract Classes
When we define a class to be final, it cannot be extended. In certain situation, we want to properties of classes to be always extended and used. Such classes are called Abstract Classes. An Abstract class is a conceptual class. An Abstract class cannot be instantiated objects cannot be created.

Abstract classes provides a common root for a group of classes, nicely tied together in a package

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Abstract Class Syntax


abstract class ClassName {
... abstract Type MethodName1(); Type Method2() { // method body }

} When a class contains one or more abstract methods, it should be declared as abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

The Shape Abstract Class


public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } } Is the following statement valid?
Shape s = new Shape();

No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Abstract Classes
public Circle extends Shape { protected double r; protected static final double PI =3.1415926535; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; } } CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Abstract Classes Properties


A class with one or more abstract methods is automatically abstract and it cannot be instantiated. A class declared abstract, even with no abstract methods can not be instantiated.

A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.
A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Abstract Classes Properties


Any class with an abstract method is automatically abstract itself and must be declared as such. An abstract class cannot be instantiated. A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of its superclass and provides an implementation (i.e., a method body) for all of them. Such a class is often called a concrete subclass, to emphasize the fact that it is not abstract. If a subclass of an abstract class does not implement all the abstract methods it inherits, that subclass is itself abstract. static, private, and final methods cannot be abstract, since these types of methods cannot be overridden by a subclass. Similarly, a final class cannot contain any abstract methods. A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a superclass for one or more subclasses that will complete the implementation. Such a class cannot be instantiated.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Example

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Examples
Which declare a compilable abstract class? (Choose all that apply.) A. public abstract class Canine { public Bark speak(); } B. public abstract class Canine { public Bark speak() { } } C. public class Canine { public abstract Bark speak(); } D. public class Canine abstract { public abstract Bark speak(); }
B is correct. abstract classes don't have to have any abstract methods. A is incorrect because abstract methods must be marked as such. C is incorrect because you can't have an abstract method unless the class is abstract. D is incorrect because the keyword abstract must come before the classname.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
public abstract class AbstractClass { public AbstractClass() { System.out.println("this is an abstract class constructor!"); } public void aMethod() { System.out.println("This is in the method in the abstract class"); } } No output compiles successfully
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

public abstract class Entity { private int id; private Color c; public void setID(int id) { this.id = id } public int getID() { return id; } public void setColor(Color c) { this.c = c; } public Color getColor() { return c; } public abstract void paint(Graphics g); } public class Point extends Entity { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public void paint(Graphics g) { g.setColor(getColor()); g.drawLine(x, y, x, y); } } CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

The Object Class


There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Object class methods

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Summary
If you do not want (properties of) your class to be extended or inherited by other classes, define it as a final class.
Java supports this is through the keyword final. This is applied to classes.

You can also apply the final to only methods if you do not want anyone to override them. If you want your class (properties/methods) to be extended by all those who want to use, then define it as an abstract class or define one or more of its methods as abstract methods.
Java supports this is through the keyword abstract. This is applied to methods only. Subclasses should implement abstract methods; otherwise, they cannot be instantiated.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Anda mungkin juga menyukai