0% found this document useful (0 votes)
26 views

Unit 2 Inheritance in JAVA

This has detailed description about inheritance and types of inheritance in JAVA....

Uploaded by

ayesha271
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)
26 views

Unit 2 Inheritance in JAVA

This has detailed description about inheritance and types of inheritance in JAVA....

Uploaded by

ayesha271
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/ 56

Unit-ii

• Inheritance –Definition,
• Single Inheritance,
• benefits of inheritance,
• Member access rules,
• super classes,
• polymorphism- method overriding,
• using final with inheritance,
• abstract classes,
• Base class object.

• Defining an interface
• Implementing an interface
• Differences between classes and interfaces
• Implements and extends keywords
• An application using an interfaces and uses of interfaces
Inheritance
-The mechanism of deriving a new class from an
existing class is known as inheritance.
-Existing class is known as base class or parent class
or super class and
-new class is known as derived class or child class or
sub class.
-In inheritance base class members are inherited to
derived class and also new members can be added to
derived class.
• By Inheritance, we are constructing new abstraction from the existing
one with extending or specializing the parents methods, and adding
new methods or properties.
• When a child class(newly defined abstraction) inherits(extends) its
parent class (being inherited abstraction), all the properties and
methods of parent class becomes the member of child class. In
addition, child class can add new data fields(properties) and
behaviors(methods), and can override methods that are inherited from
its parent class.
Types of Inheritance

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
Contd..
Single Inheritance Hierarchical Inheritance

A A X X

B B A B C A B C

NOT SUPPORTED BY JAVA


MultiLevel Inheritance Multiple Inheritance
SUPPORTED BY JAVA
A A A B A B

B B

C C
C C
Syntax of Derived class:
class subclass-name extends superclass-name {
// body of class
}
Single Inheritance
-Derivation of a class from only one base class is called
single inheritance.
A base class:
class A
{
B
//members of A
}
Derived class syntax:
class B extends A
{
//members of B
}
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
/* The subclass has access to all public members of
void showij() {
System.out.println("i and j: " + i + " " + j); its superclass. */
} subOb.i = 7;
} subOb.j = 8;
// Create a subclass by extending class A. subOb.k = 9;
class B extends A { System.out.println("Contents of subOb: ");
int k; subOb.showij();
void showk() { subOb.showk();
System.out.println("k: " + k);
}
System.out.println();
void sum() { System.out.println("Sum of i, j and k in subOb:");
System.out.println("i+j+k: " + (i+j+k)); subOb.sum();
} }
} }
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
The Benefits of Inheritance

• Software Reusability ( among projects )


– Code ( class/package ) can be reused among the projects.
– Ex., code to insert a new element into a table can be written
once and reused.

• Code Sharing ( within a project )


– It occurs when two or more classes inherit from a single parent
class.
– This code needs to be written only once and will contribute only
once to the size of the resulting program.
• Increased Reliability (resulting from reuse and
sharing of code)
– When the same components are used in two or more
applications, the bugs can be discovered more quickly.

• Consistency of Interface(among related objects )


– When two or more classes inherit from same superclass, the
behavior they inherit will be the same.
– Thus , it is easier to guarantee that interfaces to similar objects
are similar.
• Software Components
– Inheritance enables programmers to construct reusable
components.

• Rapid Prototyping (quickly assemble from pre-


existing components)
– Software systems can be generated more quickly and easily by
assembling preexisting components.
– This type of development is called Rapid Prototyping.
• Polymorphism and Frameworks (high-level
reusable components)
– Normally, code reuse decreases as one moves up the levels of
abstraction.

– Lowest-level routines may be used in several different projects,


but higher-level routines are tied to a particular application.

– Polymorphism in programming languages permits the


programmer to generate high-level reusable components that
can be tailored to fit different applications by changes in their
low-level parts.
• Information Hiding
– The programmer who reuses a software component needs only
to understand the nature of the component and its interface.
– It is not necessary for the programmer to have detailed
information such as the techniques used to implement the
component.
The Costs of Inheritance
• Execution Speed
– Inherited methods, which must deal with subclasses, are often
runs slowly than specialized code.
• Program Size
– The use of any software library increases program size.

• Message-Passing Overhead
– Message passing is more costly than invoking procedures.

• Program Complexity
– Overuse of inheritance often increases program complexity.
 Member access rules
 A subclass includes all of the members of its superclass
except private members.
 Remember
 A class member that has been declared as private will
remain private to its class. It is not accessible by any
code outside its class, including subclasses.
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;

void sum() {

total = i + j; // ERROR, j is not accessible here


}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
// Create a superclass.
class A {
int i; // public by default
protected int j;
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;

void sum() {

total = i + j; // j is accessible here


}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
super uses

super has two general forms.


 The first calls the superclass constructor.
 The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
Using super to Call Superclass Constructors

 A subclass can call a constructor method defined by its superclass by use


of the following form of super:

super(parameter-list);

 parameter-list specifies any parameters needed by the constructor in


the superclass.
 super( ) must always be the first statement executed inside a subclass
constructor.
class Box{
Box(){
System.out.println("inside default Constructor of Box");
}
Box(int a){
System.out.println("inside parameterized Constructor of Box"+a);
}
}
class BoxSmall extends Box{
BoxSmall(int b){
super();
System.out.println("inside parameterized Constructor of BoxSmall");
}
}
class TestSuper{
public static void main(String args[]){
BoxSmall s1=new BoxSmall(20);
}
}
A Second Use of super
 The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.

general form:
super.member

 Here, member can be either a method or an instance variable.


 This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.
Ex:
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
When Constructors Are Called

In a class hierarchy constructors are called in order of derivation, from


superclass to subclass.
super(…) must be the first statement executed in a subclass’ constructor.
If super(…) is not used, the default constructor of each superclass will be
executed.
Implicitly default form of super ( super() ) will be invoked in each
subclass to call default constructor of superclass
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
polymorphism- method overriding
 Polymorphism: to assign multiple meanings to the same method name
Implemented using late binding.
Late binding or dynamic binding (run-time binding):
 Method to be executed is determined at execution time, not at compile time.
• Method Overriding
 When a method in a subclass has the same
 name
 signature and
 return type
– as a method in its superclass, then the method in the subclass is said
to be overriden the method in the superclass.
– When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
– The version of the method defined by the superclass will be hidden .
class A{
int i,j; class Override
A(int a,int b){ {
i=a; public static void main(String args[])
i=b; {
B subob=new B(3,4,5);
}
Subob.show();
void show(){ }
System.out.println(“i and j :”+i+” “+j); }
}}
class B extends A{
int k;
B(int a,int b.int c){
super(a,b);
k=c;
}
void show(){
System.out.println(“k=:”+k);
}}
class A{
int i,j;
class Override
A(int a,int b){
{
i=a; public static void main(String args[])
i=b; {
} B subob=new B(3,4,5);
void show(){ Subob.show();
System.out.println(“i and j :”+i+” “+j); }
}} }
class B extends A{
int k;
B(int a,int b.int c){
super(a,b);
k=c;
}
void show(){
super.show(); // this calls A's show()
System.out.println(“k=:”+k);
}}
Dynamic Method Dispatch
 Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.

 When an overridden method is called through a superclass reference, the


method to execute will be based upon the type of the object being referred
to at the time the call occurs.
 Not the type of the reference variable.
class A
{
void callme()
{
System.out.println(“Inside A’s callme method”); class Dispatch
} {
} Public static void main(String args[])
{
class B extends A
A a=new A();
{ B b=new B();
void callme() C c=new C();
{ A r; // obtain a reference of type A
System.out.println(“Inside B’s callme method”);
} r=a; // r refers to an A object
}
r.callme(); // calls A's version of callme
class C extends A
{ r=b; // r refers to an B object
void callme() r.callme(); // calls B's version of callme
{
System.out.println(“Inside C’s callme method”); r=c; // r refers to an C object
} r.callme(); // calls C's version of callme
} }
}
Using final with Inheritance

 The keyword final has three uses.


 To create constant
 To prevent overriding
 To prevent inheritance
To create constant
 A variable which is declared as final can not be modified latter.
 This means that you must initialize a final variable when it is
declared.
Ex:-
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Using final to Prevent Overriding
 Methods declared as final cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
}
}
Using final to Prevent Inheritance
 classes declared as final cannot be inherited.
 Declaring a class as final implicitly declares all of its methods as
final.
 It is illegal to declare a class as both abstract and final, because
an abstract class is incomplete by itself and depends upon its
subclasses to provide complete implementations.

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Abstract Classes
 A method that has been declared but not defined is an abstract method.

 Any class containing an abstract method is an abstract class

 You must declare the abstract method with the keyword abstract:
 abstract type name(parameter-list);

 You must declare the class with the keyword abstract:


 abstract class MyClass {...}

 An abstract class is incomplete


 It has “missing” method bodies

 You cannot instantiate (create a new instance of) an abstract class


Contd..
 You can extend (subclass) an abstract class.
 If the subclass defines all the inherited abstract methods, it is
“complete” and can be instantiated
 If the subclass does not define all the inherited abstract methods, it is
also an abstract class.

 You can declare a class to be abstract even if it does not contain any
abstract methods
 This prevents the class from being instantiated.
Ex:-
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
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();
}
}
Base Class Object
• In java, all classes use inheritance.
• If no parent class is specified explicitly, the base class Object is implicitly inherited.
• All classes defined in Java, is a child of Object class, which provides minimal
functionality guaranteed to be common to all objects.
Method Purpose
Object clone( ) Creates a new object that is the same as the object
being cloned.
boolean equals(Object object) Determines whether one object is equal
to another.
void finalize( ) Called before an unused object is recycled.
class getClass( ) Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the
invoking object.
void notify( ) Resumes execution of a thread waiting on the
invoking object.
void notifyAll( ) Resumes execution of all threads waiting on the
invoking object.
String toString( ) Returns a string that describes the object.
void wait( ) Waits on another thread of execution.
void wait(long milliseconds)
void wait(long milliseconds,int nanoseconds).
Interfaces
• Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are declared
without any body.
• Any number of classes can implement an interface.
• One class can implement any number of interfaces.
Defining an Interface
• The general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Example:
interface Callback {
void callback(int param);
}
Contd..
• Here, access is either public or not used.
– Default indicates, the interface is only available to other
members of the package in which it is declared.
– Public indicates, the interface can be used by any other
code.

• Variables can be declared inside of an interface.


• They are implicitly final and static, meaning they cannot be
changed by the implementing class.
• They must be initialized with a constant value
• All methods and variables are implicitly public if the
interface, itself, is declared as public.
Implementing interfaces
– Once an interface has been defined, one or more classes can implement that
interface.
– The general form of a class that implements an interface :
access class classname [extends superclass][implements interface [,interface...]]
{
// class-body
}
• If a class implements more than one interface, the interfaces are separated with a
comma.
• The methods that implement an interface must be declared as public.
• The type signature of the implementing method must match exactly the type
signature specified in the interface definition
 Example class that implements the Callback interface
interface Callback {
void callback(int param);
}

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
Notice that callback( ) is declared using the public access specifier.

Note: When you implement an interface method, it must be declared


as public.
• Classes that implement an interfaces can define
additional members of their own.
//Example for a class which contain both interface and non interface methods
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}

void nonIfaceMeth() {
System.out.println(“Non Interface Method….");
}
}
Accessing Implementations Through Interface
References
• Any instance of any class that implements the interface can be referred by
an interface variable.
• When you call a method through an interface variable, the correct
version will be called based on the actual instance of the class referred by
the variable.
• This is one of the key features of interfaces.
interface Callback {
void callback(int
param);
}

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
//Callback cb;
//Client c=new Client();
//cb=c;
//cb.callback(42);
}
}

Output:
callback called with 42
Partial Implementations
If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.
abstract class Incomplete implements Callback{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
 If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.
 Here, the class Incomplete does not implement callback( ) and must be
declared as abstract.
 Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.
Variables in Interfaces
You can define variables in an interface but implicitly they are final variables.
That is you can’t modify them .

FinalTest.java
class FinalImpl implements FinalDemo{
public void show(){
System.out.println("FinalTest :Show()");
}
FinalDemo.java }
interface FinalDemo{ class FinalTest{
int i=100; public static void main(String sree[]){
void show(); FinalImpl fi=new FinalImpl();
} fi.show();
//fi.i=200; can’t assign a value to variable i
System.out.println("FinalDemo Varaible i :"+fi.i);

}
} Output:
FinalTest :Show()
FinalDemo Varaible i :100
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.

The syntax is the same as for inheriting classes.

When a class implements an interface that inherits another interface, it must


provide implementations for all methods defined within the interface inheritance
chain.
public void meth2() {
// One interface can extend another.
System.out.println("Implement
interface A {
meth2().");
void meth1();
}
void meth2();
public void meth3() {
}
// B now includes meth1() and meth2() -- it adds System.out.println("Implement
meth3(). meth3().");
interface B extends A { }
void meth3(); }
} class IFExtend {
// This class must implement all of A and B public static void main(String arg[]) {
class MyClass implements B { MyClass ob = new MyClass();
public void meth1() { ob.meth1();
System.out.println("Implement meth1()."); ob.meth2();
} ob.meth3();
}
} Output:
Implement meth1().
Implement meth2().
Implement meth3().
interface Callback { class TestIface2 {
void callback(int param); public static void main(String args[]) {
} Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
class Client implements Callback { c = ob; // c now refers to AnotherClient object
// Implement Callback's interface c.callback(42);
public void callback(int p) { } }
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println(“NonInterface Method….");
}
}

// Another implementation of Callback.


class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback"); Output:
System.out.println("p squared is " + (p*p)); callback called with 42
}
Another version of callback
}
p squared is 1764
Class Vs Interface
 The methods of an Interface are all abstract methods. They cannot have bodies.
An interface can only define constants.
 You cannot create an instance from an interface.

 An interface can only be implemented by classes or extended by other


interfaces.

 Interfaces have no direct inherited relationship with any particular class, they
are defined independently.

 Interfaces themselves have inheritance relationship among themselves.

 A class can implement more than one interface. By contrast, a class can only
inherit a single superclass (abstract or otherwise).

Abstract Class Vs Interface
An abstract class is written when there are some common features shared by all the objects.
 An interface is written when all the features are implement differently in different objects.
 When an object class is written, it is the duty of the programmer to provide sub classes to it.
 An interface is written when the programmer wants to leave the implementation to the third party
vendors.
 An abstract class contains some abstract methods and also some concrete methods.
 An interface contains only abstract methods.
 An abstract class can contain instance variables also.
 An interface can not contain instance variables. It contains only constants.
 All the abstract methods of the abstract class should be implemented in its sub classes.
 All the (abstract) methods of the interface should be implemented in its implementation classes.
 Abstract class is declared by using the keyword abstract.
 Interface is declared using the keyword interface.
 A class can implement more than one interface.
 An abstract class can only inherit a single super class (abstract or otherwise).
 Interfaces have no direct inherited relationship with any particular class, they are defined
independently. Interfaces themselves have inheritance relationship among themselves.
• Define an interface “GeometricShape” with methods area ()
and perimeter () (Both methods return type and parameter list
should be void and empty respectively).
• Define classes like Triangle, Rectangle and Circle
implementing the “GeometricShape” Interface and also define
“ExecuteMain” class in which includes main method to test
the above class
Uses of Interface
 To reveal an object's programming interface (functionality of the object)
without revealing its implementation.
– This is the concept of encapsulation.
– The implementation can change without affecting the caller of the
interface.

 To have unrelated classes implement similar methods (behaviors).


– One class is not a sub-class of another.

 To model multiple inheritance.


– A class can implement multiple interfaces while it can extend only one
class.

You might also like