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

Ch3 Inheritance Interfaces

Uploaded by

aadi.n.harale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Ch3 Inheritance Interfaces

Uploaded by

aadi.n.harale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Inheritance

Inheritance is one of the most important feature of Object Oriented Programming. This concept
is used for reusability purpose. Inheritance is the mechanism through which we can derive new
class from existing class. The derived class is called as subclass and the class from which we
are deriving the subclass is called the base class or the parent class. To derive a class in java the
keyword extends is used. It allows the creation of hierarchical classifications of classes. The
concept of inheritance is used to make the things from general to more specific. Using
inheritance, a general class can be created that defines traits common to a set of related items.
This class can be inherited by other, more specific classes, each adding those things that are
unique to it.

A sub-class is a specialized version of its super-class:


1) has all non-private members of its super-class
2) may provide its own implementation of super- class method
3) Objects of a sub-class are a special kind of objects of a super-class.
Benefits of Inheritance: Reusability
Once behaviour (method) is defined in a super class, that behaviour is automatically inherited by
all subclasses. Thus, write a method only once and it can be used by all subclasses.

Once a set of properties (fields) are defined in a super class, the same set of properties are
inherited by all subclasses

A class and its children share common set of properties. A subclass only needs to implement
differences between itself and the parent.

General Form
class derived-class extends base-class {

variable declaration;
method declaration;
}

• The keyword extends is used in Java for inheritance.

1
• A class that extends another class is said to be a subclass. It is also known as a child
class or a derived class.

• The class it extends is called a super class. Sometimes the super class is called a base
class or a parent class.

• A subclass can also modify its method members. This is referred to as overriding.

• A subclass inherits the non-private members of it’s super class.

Example -

class Boy {
String name;
int age;
Boy(){
name=" Ameya";
age=21;
}
void display(){
System.out.println("Name: " + name);
System.out.println("Age: " + age);

2
}
}
class Student extends Boy{
int roll,marks;
Student(){
roll=99;
marks=81;
}
void putData(){
System.out.println("Roll: " + roll);
System.out.println("Marks: " + marks);
}
}
class BSC {
public static void main(String args[]){
Student s=new Student();
s.display();
s.putData();
}
}

Types of Inheritance
 Single ( only one super class)
 Multiple (several super classes)
 Hierarchical (one super class, many sub classes)
 Multilevel (derived from a derived class)
 Multiple inheritance is not directly supported by Java. It is implemented through
Interfaces.

Keyword super
3
The keyword super is used in a subclass to refer to members of the super class. It is used in
two ways:
 To invoke a constructor of the super class. For example (note: the keyword new is not
used):
• super();
• super(parameters);
Here parameter list is the list of the parameter requires by the constructor in the
super class. super must be the first statement executed inside a super class
constructor. If we want to call the default constructor then we pass the empty
parameter list.

 To call a superclass’ method (it is only necessary to do so when you override the
method). For example:
• super.superclassMethodName();
• super.superclassMethodName(parameters);
class Boy{
String name;
int age;
void getData(){
name=" Ameya";
age=21;
}
void display(){
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Student extends Boy {
int roll,marks;
void getData(){
super.getData();
roll=99;
marks=81;
}
void putData(){
System.out.println("Roll: " + roll);

4
System.out.println("Marks: " + marks);
}
}
class BSO1 {
public static void main(String args[]){
Student s=new Student();
s.getData();
s.display();
s.putData();
}
}

Overriding methods
Subclasses inherit all methods from their superclass. Sometimes, the implementation of the
method in the superclass does not provide the functionality required by the subclass. In these
cases, the method must be overridden.To override a method, provide an implementation in the
subclass. The method in the subclass MUST have the exact same signature as the method it is
overriding.

Example: Overriding Methods

The following is implementation for the getName method in the Boy super class-

class Boy {
---------;
String getName(){
System.out.println(“Base: getName");
return name;
}
}
class Student extends Boy{
------------;
String getName(){
System.out.println(" Derived : getName");
return name;

5
}
----------------;
}
 To override the getName method of the super class Boy in the subclass Student,
reimplement the method with the same signature

 Now, when we invoke the getName method of an object of the subclass Student, the
getName method of the Student would be called, and the output would be,

Derived : getName

 Only non-private methods can be overridden because private methods are not visible in
the subclass.

 Note: Static methods cannot be overridden.


 Note: Fields cannot be overridden.
 In the above two cases, when you attempt to override them, you are really hiding them.

this Keyword
The keyword this helps to avoid name conflicts.

 The program declares the name of instance variable and local variables same. Now to
avoid the conflict between them we use this keyword.

 In the example, this.length and this.breadth refers to the instance variable length and
breadth while length and breadth refers to the arguments passed in the method.

class Rectangle{
int length, breadth;
void setData(int length, int breadth){
this.length=length;
this.breadth=breadth;
}

6
int calculate(){
return(length*breadth);
}
}
public class UseOfThis{
public static void main(String[] args){
Rectangle r1=new Rectangle();
r1.setData(5,6);
int area = r1.calculate();
System.out.println(“ Area of Rectangle is : " + area);
}

Multilevel inheritance:
A new class is derived from another derived class.

class Boy {
String name;
int age;
void accept() {
name=" Ameya";
age=21;
}
void display() {
System.out.println(" Name: " + name);
System.out.println(" Age: " + age);
}
}
class Student extends Boy {
int roll,marks;
void getData() {
roll=99;
marks=81;
}

7
void putData() {
System.out.println(" Roll: " + roll);
System.out.println(" Marks: " + marks);
}
}
class Test extends Student {
int m1,m2;
void get(int a, int b) {
m1=a;
m2=b;
}
void put() {
System.out.println(" m1= "+ m1);
System.out.println(" m2= "+ m2);
}
}

class MLEVEL {
public static void main(String args[]) {
Test T= new Test();
T.accept();
T.display();
T.getData();
T.putData();
T.get(89,91);
T.put();
}
}

8
Hierarchical inheritance:
In this case many sub classes are derived from one super class.

class Employee {
String name;
int age;
void accept() {
name=" Ajay";
age=45;
}
void display() {
System.out.println(" Name: " + name);
System.out.println(" Age: " + age);
}
}
class Manager extends Employee {
int grade;
String dept;
void getData() {
grade=2;
dept="Sales";
}
void putData() {
System.out.println(" Grade: " + grade);
System.out.println(" Dept: " + dept);
}
}
class Engineer extends Employee {
String project;
String teamid;
void get() {
project="ERP";
teamid="E-7";
}
void put() {
System.out.println(" Project= "+ project);
System.out.println(" Teamid= "+ teamid);
}
}
class Hie {
public static void main(String args[]) {
Manager M=new Manager();
M.accept();
M.display();
M.getData();
M.putData();

9
Engineer E=new Engineer();
E.accept();
E.display();
E.get();
E.put();
}
}

Interfaces
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.

An interface is similar to a class in the following ways:

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

10
Declaring Interfaces:
The interface keyword is used to declare an interface.

An interface is defined much like a class. This is 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:
//Program to define and implement an interface
// the same interface is implemented by two different classes
interface Area{
final float PI = 3.1425926F; //static and final constant.
float compute(float x, float y);
}

class Triangle implements Area{


public float compute(float x, float y){
return (0.5*x*y);
}
}

class Rectangle implements Area{


public float compute(float x, float y){
return (x*y);
}
}

11
class InterfaceTest{
public static void main (String args[ ]){
Rectangle rect = new Rectangle();
Triangle tr =new Triangle();
Area area;
area = rect;
System.out.println("area of rectangle = " + area.compute(10,20));
area = tr;
System.out.println("area of circle = " + area.compute(10,10));
}
}

//Program to define and implement an interface


//The Test class extends Boy class and implements Student interface
class Boy
{
String name;
int age;
int roll,marks;

void accept()
{
name=" Ameya";
age=21;
roll=99;
marks=81;
}
}

interface Student
{
int totmarks=200;
void putData();

12
class Test extends Boy implements Student
{
int m1,m2;
void get(int a, int b)
{
m1=a;
m2=b;
}
void display()
{
System.out.println(" m1= "+ m1);
System.out.println(" m2= "+ m2);
System.out.println(" Avg= "+ (m1+m2)*100/totmarks);

}
public void putData()
{
System.out.println(" Name: " + name);
System.out.println(" Age: " + age);
System.out.println(" Roll: " + roll);
System.out.println(" Marks: " + marks);
}
}

class I1
{
public static void main(String args[])
{
Test T=new Test();
T.accept();
T.get(89,91);
T.putData();
T.display();
}
}

13
Classes and Interfaces: Similarities
1. A super class provides a secondary data type to objects of its subclasses.
2. An abstract class cannot be instantiated.
3. An interface provides a secondary data type to objects of classes that implement that
interface.
4. An interface cannot be instantiated.
5. A concrete subclass of an abstract class must define all the inherited abstract methods.
6. A class can extend another class. A subclass can add methods and override some of its
super class’s methods.
7. A concrete class that implements an interface must define all the methods specified by
the interface.
8. An interface can extend another interface (called its super interface) by adding
declarations of abstract methods.
9. A class can extend only one class. A class can have fields. A class defines its own
constructors (or gets a default constructor). A class can implement any number of
interfaces.
10. An interface cannot have fields. An interface has no constructors.

Differences:
 A concrete class has all its methods defined.
 An abstract class usually has one or more abstract methods.
 Every class is a part of a hierarchy of classes with Object at the top.
 All methods declared in an interface are abstract.
 An interface may belong to a small hierarchy of interfaces, but this is not as common.

Advantages of Interfaces
 Interfaces provide a standard set of methods for a group of classes. This is Java’s
implementation of an Abstract Data Type (ADT).

14
Overloading and Overriding

 Overloading is an example of polymorphism. (operational / parametric)


 Overriding is an example of runtime polymorphism (inclusive)
 A method can have the same name as another method in the same class, provided it forms
either a valid overload or override.

Overloading Overriding
Signature has to be different. Just a Signature has to be the same. (including the return type)
difference in return type is not enough.
Accessibility may vary freely. Overriding methods cannot be more private than the
overridden methods.

Exception list may vary freely. Overriding methods may not throw more checked
exceptions than the overridden methods.

Just the name is reused. Methods are Related directly to sub-classing. Overrides the parent
independent methods. Resolved at class method. Resolved at run-time based on type of the
compile-time based on method signature. object.

Can call each other by providing Overriding method can call overridden method by
appropriate argument list. super.methodName(), this can be used only to access
the immediate super-class's method. super.super won't
work. Also, a class outside the inheritance hierarchy
can't use this technique.

Methods can be static or non-static. static methods don't participate in overriding, since they
are resolved at compile time based on the type of
reference variable.

A static method and a non-static method cannot have


the same name and signature (if signatures are different,
it would have formed a valid overload)

There's no limit on number of overloaded Each parent class method may be overridden at most
methods a class can have. once in any sub-class. (That is, you cannot have two
identical methods in the same class)

15
Variables can also be overridden, it's known as shadowing or hiding. But, member variable
references are resolved at compile-time. So at the runtime, if the class of the object referred by a
parent class reference variable, is in fact a sub-class having a shadowing member variable, only the
parent class variable is accessed, since it's already resolved at compile time based on the reference
variable type. Only methods are resolved at run-time.

public class Shadow {


public static void main(String s[]) {
S1 s1 = new S1();
S2 s2 = new S2();
System.out.println(s1.s); // prints S1
System.out.println(s1.getS()); // prints S1
System.out.println(s2.s); // prints S2
System.out.println(s2.getS()); // prints S2
s1 = s2;
System.out.println(s1.s); // prints S1, not S2 -
// since variable is resolved at compile time
System.out.println(s1.getS()); // prints S2 -
// since method is resolved at run time
}
}
class S1 {
public String s = "S1";
public String getS() {
return s;
}
}
class S2 extends S1{
public String s = "S2";
public String getS() {
return s;
}
}

16
In the above code, if we didn't have the overriding getS() method in the sub-class and if we call
the method from sub-class reference variable, the method will return only the super-class
member variable value. For explanation, see the following points.
Also, methods access variables only in context of the class of the object they belong to. If a sub-
class method calls explicitly a super class method, the super class method always will
access the super-class variable. Super class methods will not access the shadowing variables
declared in subclasses because they don't know about them. (When an object is created,
instances of all its super-classes are also created.) But the method accessed will be again subject
to dynamic lookup. It is always decided at runtime which implementation is called. (Only static
methods are resolved at compile-time)

public class Shadow2 {


String s = "main";
public static void main(String s[]) {
S2 s2 = new S2();
s2.display(); // Produces an output - S1, S2
S1 s1 = new S1();
System.out.println(s1.getS()); // prints S1
System.out.println(s2.getS()); // prints S1 - since super-class method
// always accesses super-class variable
}
}
class S1 {
String s = "S1";
public String getS() {
return s;
}
void display() {
System.out.println(s);
}
}
class S2 extends S1{

17
String s = "S2";
void display() {
super.display(); // Prints S1
System.out.println(s); // prints S2
}
}

18
Dynamic Method Dispatch

Method overriding forms the basis for 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. Java implements run-time polymorphism using Dynamic
method dispatch.
It is based on the fact that a superclass reference variable can refer to a subclass object. Java
uses this fact to resolve calls to overridden methods at run time.

When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the time
the call occurs. Thus, this determination is made at run time. When different types of objects are
referred to, different versions of an overridden method will be called. In other words, it is the type
of the object being referred to (not the type of the reference variable) that determines which
version of an overridden method will be executed. Therefore, if a superclass contains a method
that is overridden by a subclass, then when different types of objects are referred to through a
superclass reference variable, different versions of the method are executed.

Here is an example that illustrates dynamic method dispatch:

// Dynamic Method Dispatch


class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}

19
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}

class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

The output from the program is shown here:

Inside A’s callme method


Inside B’s callme method
Inside C’s callme method

This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type
A, B, and C are declared. Also, a reference of type A, called r, is declared.
The program then assigns a reference to each type of object to r and uses that reference to
invoke callme( ). As the output shows, the version of callme( ) executed is determined by the
type of object being referred to at the time of the call.

20

You might also like