0% found this document useful (0 votes)
15 views23 pages

Java Inheritance and Interfaces Explained

This document covers Object Oriented Programming with Java, focusing on inheritance, interfaces, and abstract classes. It explains key concepts such as inheritance basics, method overriding, dynamic method dispatch, and the use of the 'super' keyword. The document also includes examples and code snippets to illustrate these concepts.

Uploaded by

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

Java Inheritance and Interfaces Explained

This document covers Object Oriented Programming with Java, focusing on inheritance, interfaces, and abstract classes. It explains key concepts such as inheritance basics, method overriding, dynamic method dispatch, and the use of the 'super' keyword. The document also includes examples and code snippets to illustrate these concepts.

Uploaded by

an2259162
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Object Oriented Programming with JAVA (BCS306A)

MODULE -3
Inheritance: Inheritance Basics, using super, Creating a Multilevel Hierarchy, When
Constructors Are Executed, Method Overriding, Dynamic Method Dispatch, Using Abstract
Classes, Using final with Inheritance, Local Variable Type Inference and Inheritance, The
Object Class.

Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private
Interface Methods.

Chapter 8, 9

Inheritance Definition:
• Inheritance is a process where new classes(child class) are made from the existing
classes(parent class).
• Parent class is also called as Super class and child class is also called as Sub class.
• A subclass inherits all the members of a superclass and adds its own unique members.
• Inheritance allows the creation of hierarchical classifications.
• Following properties are inherited from Parent class to child class:
o Instance variables of Super class o
Methods of super class

• Advantages of Inheritance:
• Code reusability
• Elimination of duplicate code

General syntax of Inheritance

class Subclass-name extends Superclass-name


{
//body of subclass
}
• The extends keyword indicates that you are making a new class from an existing class.
• The meaning of "extends" is to increase the functionality.

Example:

class A
{ int i;
void showi()
{
[Link](i);
}
}

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 1


Object Oriented Programming with JAVA (BCS306A)

class B extends A
{
int k;
void shock()
{
[Link](k);
}
void sum()
{
[Link](i+k);
}
}
class Mainclass
{
public static void main(String[] args)
{
A ObA = new A();
B ObB = new B();
Output:
10
ObA.i = 10; 7
[Link](); 9
16
ObB.i = 7;

ObB.k = 9;
[Link]();
[Link]();
[Link]();
}
}

//Another Simple Example:


class Employee
{
float salary=4000;
}
class Programmer extends Employee
{
int bonus=1000;
public static void main(String args[])
{
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 2


Object Oriented Programming with JAVA (BCS306A)

}
}

Output:
Programmer salary is:4000.0
Bonus of programmer is:1000

Types of Inheritance:

Note:
• Java does not support multiple Inheritance, i.e. the inheritance of multiple super classes
into a single subclass is not possible.

Member Access and Inheritance:


• A subclass cannot access private members of the superclass.

/* This program contains an error and will not compile. */ class A


{
int i;
// default access
private int j; // j is private to A
void setij(int x, int y)
{ i = x; j =
y;
}
}

class B extends A
{ int total;
void sum()

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 3


Object Oriented Programming with JAVA (BCS306A)

{
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String[] args)
{
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}

//Another Example : class


Box
{
double width;
double height;
double depth;

double volume()
{
return (width * height * depth);
}
}
class BoxWeight extends Box // Box is extended to include weight.
{
double weight;
BoxWeight(double w, double h, double d, double m) //constructor
{
width = w;
height = h;
depth = d;
weight = m;
}
}
class Mainclass
{
public static void main(String[] args)
{
BoxWeight mybox = new BoxWeight(10, 20, 15, 34.3);

[Link]("Volume of mybox is " + [Link]());

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 4


Object Oriented Programming with JAVA (BCS306A)

[Link]("Weight of mybox is " + [Link]);


}
}

Output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3

“super” keyword

• The super keyword allows a subclass to access members (methods or variables) of its
superclass.
• It is particularly useful when the subclass has members with the same names as the
superclass, or when invoking a constructor of the superclass.
• The super keyword serves a special purpose in the context of inheritance.

• Usage of java super Keyword


1. Used to refer immediate parent class instance variable.
2. Used to invoke immediate parent class method.
3. Used to invoke immediate parent class constructor.

1. super is used to refer immediate parent class instance variable.


• We can use super keyword to access the data member or field of parent class.
• It is used if parent class and child class have same fields.
• Sub-class variable hides the super-class variable in class sub-class.

Example :

class Animal
{
String color = "white"; // name : color
}

class Dog extends Animal


{
String color = "black"; // name : color

void printColor()
{
[Link](color); // prints color of Dog class
[Link]([Link]); // prints color of Animal
class
}
}

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 5


Object Oriented Programming with JAVA (BCS306A)

class Mainclass
{
public static void main(String[ ] args) Output:
{ black white
Dog d=new Dog(); [Link]();
}
}

2. super is used to invoke super-class(parent class) constructor.

class A
{
int i,j;
A(int a, int b)
{ i=a;
j=b;
}
void addij()
{
[Link](i+j);
}
}
class B extends A
{ int k;
B(int a, int b, int c)
{
super(a,b); // calling a superclass constructor
k=c;
}

void addik()
{
[Link](i+k);
}
}
class Mainclass
{ Output:
public static void main(String[ ] args) 3
{ 4
B b=new B(1,2,3);
[Link]();
[Link]();
}

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 6


Object Oriented Programming with JAVA (BCS306A)

3. super is used to invoke super-class(parent class) method.

class Animal
{
void eat()
{
[Link]("All Animals can eat...");
}
}
class Dog extends Animal
{
void eat() // eat() overridden
{
[Link]("eating bread...");
}
void bark()
{
[Link]("barking...");
}
void work()
{
[Link](); // calling parent method
bark();
}
}

class Mainclass
{
public static void main(String args[]) Output:
{ All Animals can eat...
Dog d=new Dog(); [Link](); barking...
}
}

Creating a Multilevel Hierarchy:


• If the level of the inheritance is two or more then we can call it as multilevel inheritance.
• It is perfectly acceptable to use a subclass as a superclass of another.
• For example, given three classes called A, B, and C, C can be a subclass of B, which is a
subclass of A. When this type of situation occurs, each subclass inherits all of the traits
found in all of its super classes.
• In this case, C inherits all aspects of B and A.

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 7


Object Oriented Programming with JAVA (BCS306A)

Example:

class A
{
double x;
A(double i)
{ x=i;
}
double display()
{
return(x);
}
}

class B extends A
{
double y;
B(double i, double j)
{ super(i); y
= j;
}
}

class C extends B
{
double z;
C(double i, double j, double k)
{ super(i, j); z
= k;
}
}
class Mainclass
{
public static void main(String args[]) Output: 10
{
C ObC= new C(10, 20, 15);
[Link]([Link]());
}
}

When Constructors Are Executed:

• When a class hierarchy is created, in what order are the constructors for the classes that
make up the hierarchy called?

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 8


Object Oriented Programming with JAVA (BCS306A)

• For example, given a subclass called B and a superclass called A, is A’s constructor called
before B’s, or vice versa?
• The answer is that in a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.
• Further, since super( ) must be the first statement executed in a subclass’ constructor,
this order is the same whether or not super( ) is used. If super( ) is not used, then the
default or parameter less constructor of each superclass will be executed.

Example:

class A
{
A()
{
[Link]("Inside A's constructor.");
}
}

class B extends A
{
B()
{
[Link]("Inside B's constructor.");
}
}
class C extends B
{
C()
{
[Link]("Inside C's constructor.");
}
}
class MainClass
{
public static void main(String[] args) Output:
{ Inside A’s constructor
C c = new C(); Inside B’s constructor
} Inside C’s constructor
}

Method Overriding:

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 9


Object Oriented Programming with JAVA (BCS306A)

• If a subclass has the same method as declared in the super class, it is known as method
overriding.
• When an overridden method is called through its subclass, it will always refer to the
subclass method
• The version of the method defined by the superclass will be hidden.

Usage of Java Method Overriding


• Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
• Method overriding is used for runtime polymorphism.

Prerequisites / Rules for Java Method Overriding


• method must have same name as in the parent class
• method must have same parameter as in the parent class.

class A
{
int i=10, j=20;
void show()
{
[Link](i + " " + j);
}
}
class B extends A
{
int k=30; void show() // this overrides
show() in A
{
[Link](k);
}
}
class Mainclass
{
public static void main(String[] args) Output:
{ 30
B ObB = new B();
[Link](); // this calls show() in B
}
}

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 10


Object Oriented Programming with JAVA (BCS306A)

If you wish to access the superclass version of an overridden method, you can do so by
using super.

class B extends A
{
int k=30; void show() // this overrides
show() in A
{
[Link](); Output:
[Link](k); 10 20
} 30
}

Dynamic Method Dispatch:


• It is a mechanism by which a call to an overridden method is resolved at run time, rather
than compile time.
• Using Dynamic method dispatch Java implements run-time polymorphism.

class A
{
void callme()
{
[Link]("Inside A's callme method");
}
}
class B extends A
{
void callme() // override callme()
{
[Link]("Inside B's callme method");
}
}
class C extends A
{
void callme() // override callme()
{
[Link]("Inside C's callme method");
}
}
class Dispatch

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 11


Object Oriented Programming with JAVA (BCS306A)

{
public static void main(String[] args) Output:
{ Inside A's callme method
A a = new A(); // object of type A Inside B's callme method
B b = new B(); // object of type B Inside C's callme method
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
[Link](); // calls A's version of callme
r = b; // r refers to a B object
[Link](); // calls B's version of callme
r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}
Using “final” with Inheritance:

• The final keyword in java is used to restrict the user. The final keyword can be used
with:
▪ variable
▪ method
▪ class

final variable: Once a final variable is assigned a value can never be changed.

class Bike
{
final int speedlimit = 100; //final variable
void run()
{
speedlimit=400; // Error-cannot assign a value to final variable
//speedlimit
}
public static void main(String args[])
{
Bike b = new Bike();
[Link]();
}
}

final method: If you make any method as final, you cannot override it.

class Bike
{

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 12


Object Oriented Programming with JAVA (BCS306A)

final void run() //final method


{
[Link]("running");
}
}
class Honda extends Bike
{
void run() //Error: run final method
{
[Link]("running safely with
100kmph");
}
}

class MainClass
{
public static void main(String[] args)
{
Honda h = new Honda();
[Link]();
}
}

final class: If you make any class as final, you cannot inherit it.

final class Bike // final class


{
int add()
{
return 10;
}
}
class Honda extends Bike // final class cannot be inherited
{
void run()
{
[Link]("running safely with
100kmph");
}
}
class MainClass
{
public static void main(String args[])
{

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 13


Object Oriented Programming with JAVA (BCS306A)

Honda h= new Honda();


[Link]();
}
}

Abstract Classes:
• An abstract class serves as a blueprint for other classes.
• Abstract classes are used to define common variables and methods that will be shared
by all subclasses.
• Any class that contains one or more abstract methods must be declared abstract.
• To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
• An abstract class cannot be directly instantiated with the new operator.

// A Simple demonstration of abstract. abstract


class A
{
abstract void callme(); // abstract method
void callmetoo() //concrete methods are still allowed in abstract
//classes
{
[Link]("This is a concrete
method.");
}
}
class B extends A
{
void callme()
{
[Link]("B's implementation of
callme.");
}
}
class Mainclass
{
public static void main(String[] args) Output:
{ B's implementation of callme.
B b = new B(); [Link](); This is a concrete method.
[Link]();
}
}

// Using abstract methods and classes.

abstract class Figure

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 14


Object Oriented Programming with JAVA (BCS306A)

{
double dim1, dim2;
Figure(double a, double b)
{
dim1 = a; dim2 = b;
}
abstract double area(); // area is now an abstract method
}

class Rectangle extends Figure


{
Rectangle(double a, double b)
{
super(a, b);
}
double area() // override area for rectangle
{
[Link]("Inside Area for
Rectangle."); return (dim1 * dim2);
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
double area()
{
[Link]("Inside Area for Triangle.");
return (dim1 * dim2 / 2);
}
}
class Mainclass
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure f; // this is OK, no object is created f = r;

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 15


Object Oriented Programming with JAVA (BCS306A)

[Link]("Area is " +
[Link]()); f = t;
[Link]("Area is " + [Link]());
}
} Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0

The Object Class:


• Object is a special class defined by Java.
• 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.
• Object defines the following methods.

Interfaces ( Chapter 9)

• An interface is a blueprint of a class. It has static constants and abstract methods.


• In other words, interfaces can have abstract methods and variables.
• The interface is a mechanism used to achieve abstraction and multiple inheritance.
There can be only abstract methods in the Java interface, not method body.
• It cannot be instantiated.

Uses of Java interface? o It is used to


achieve abstraction.
o Multiple inheritance.

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 16


Object Oriented Programming with JAVA (BCS306A)

Internal addition by the compiler


• Interface fields are public, static and final by default, and the methods are public and
abstract.

The relationship between classes and interfaces


• A class extends another class, an interface extends another interface, but a class
implements an interface.

Defining an Interface : An interface is defined much like a class. Synatx:

access interface_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value; type final-
varname2 = value;
//...
}
Example1:

interface printable
{
void print();
int x=100;
}
class A6 implements printable
{
public void print()
{
[Link]("Hello");

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 17


Object Oriented Programming with JAVA (BCS306A)

}
}
class Mainclass
{
public static void main(String args[]) OUTPUT:
{ Hello
A6 obj = new A6(); [Link](); 100
[Link](obj.x);
// obj.x=100; Error: cannot assign a value to final variable x
}
}

Multiple inheritance in Java by interface:

• If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

Example:

interface Printable // interface


{ void print();
}

interface Showable // interface


{
void show();
}
class A7 implements Printable, Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 18


Object Oriented Programming with JAVA (BCS306A)

}
class Mainclass
{
public static void main(String args[]) OUTPUT:
{ Hello
A7 obj = new A7(); [Link](); Welcome
[Link]();
}
}

Interface inheritance
• A class implements an interface, but one interface extends another interface. interface
Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class Test implements Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}
}
class Mainclass
{
public static void main(String args[])
{ OUTPUT:
Test obj = new Test (); Hello
[Link](); [Link](); Welcome
}
}
Default Interface Methods:
• The non-abstract methods which are defined inside the interface are called as Default
Interface methods.
• The default method is used to define a method with default implementation. You can
override default method also to provide more specific implementation for the method.

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 19


Object Oriented Programming with JAVA (BCS306A)

interface Sayable
{
default void say()
{
[Link]("Hello, this is default
method");
}
void sayMore(String msg);
}
class DefaultMethods implements Sayable
{
public void sayMore(String msg) // implementing abstract method
{
[Link](msg);
}
}
class Mainclass
{ OUTPUT:
public static void main(String[] args) Hello, this is default method
{ Work is worship
DefaultMethods dm = new
DefaultMethods();
[Link](); // calling default method
[Link]("Work is worship"); // calling abstract method
}
}

Static Methods inside Interface:


• static methods can be defined inside the interface.
• Static methods are used to define utility methods.
• Static methods are nowhere related to objects.
• Static methods can be accessed using Interface name.

interface Sayable
{
static void say()
{
[Link](“Hellooooo”);
}
}
class DefaultMethods implements Sayable
OUTPUT:
Hellooooo
Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 20
Object Oriented Programming with JAVA (BCS306A)

{
public static void main(String[] args)
{
[Link](); // calling static method
}
}

Private Interface Methods:


• private methods cab be created inside an interface.
• private methods of interface help to share common code between non-abstract
methods.

interface Sayable
{
default void say()
{
saySomething();
}
private void saySomething() // Private method inside interface
{
[Link]("Hello... I'm private
method");
}
}
public class PrivateInterface implements Sayable
{
public static void main(String[] args)
{
PrivateInterface s = new PrivateInterface();
[Link]();
}
}
OUTPUT:
Hello... I'm private method

REVIEW QUESTIONS:
1. Define inheritance in Java.
2. What members of a superclass are not inherited by a subclass?
3. What are the two main advantages of using inheritance?
4. Explain the general syntax for inheritance in Java.
5. What will be the output of the following code?

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 21


Object Oriented Programming with JAVA (BCS306A)

6. What types of inheritance are supported in Java?


7. What is multilevel inheritance? Provide an example of how it works.
8. What is the “super” keyword used for in Java?
9. Provide an example of how the “super” keyword is used to:
• Access a superclass instance variable.
• Call a superclass method.
• Invoke a superclass constructor.
10. What is method overriding? What rules must be followed for method overriding in
Java?
11. Explain runtime polymorphism with an example involving method overriding.
12. What is dynamic method dispatch in Java? How does it relate to method overriding?
13. What does the “final” keyword do when applied to a variable, method, or class?
Provide examples for each case.
14. What is an abstract class in Java? What is the purpose of abstract methods within an
abstract class?
15. Explain the significance of the “Object” class in Java.

1. Define an interface in Java. What are the key characteristics of an interface?


2. What is the purpose of an interface in Java? How does it differ from a class?

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 22


Object Oriented Programming with JAVA (BCS306A)

3. Explain the syntax for defining an interface in Java. Provide an example of an interface
declaration.
4. What types of members can an interface have in Java?
5. What is the difference between “implements” and “extends” in Java when dealing with
interfaces and classes?
6. Can an interface contain concrete (non-abstract) methods?
7. What is the significance of the “default” keyword in interfaces?
8. Provide an example of a default method in an interface.
9. How are “static” methods used inside an interface? Provide an example.
10. Explain the role of “private” methods in interfaces.
11. How are they used and why are they beneficial?
12. Describe how multiple inheritance is achieved in Java using interfaces.
13. What is the key difference between class inheritance and interface inheritance?
14. Can a class implement multiple interfaces?
15. Provide an example where a class implements two or more interfaces.
16. What happens if a class implements two interfaces with the same method signature?
17. How does Java resolve this conflict?
18. Can we instantiate an interface in Java?
19. Provide an example where one interface extends another interface.
20. Explain how to call a static method of an interface.
21. What are the restrictions on the fields (variables) inside an interface?
22. Explain the purpose of the “default” method in interfaces.
23. Can a class extend another class and implement multiple interfaces at the same time?
24. Provide an example of an interface with a private method.

Programming is a journey, not a destination.


Every line of code is a step forward.
Keep moving, keep coding

Prepared By : Linda.R Asst Professor in CSE, Dr. TTIT, KGF 23

You might also like