Inheritance-Interface
Inheritance-Interface
Inheritance:
1. Introduction
• Inheritance is the backbone of object-oriented programming (OOP).
• It is the mechanism by which a class can acquire properties and methods of another
class.
• Using inheritance, an already tested and debugged class program can be reused for
some other application.
• Super class This is the existing class from which another class, that is, the subclass is
generally derived.
• In Java, several derived classes can have the same super class.
• Subclass A class that is derived from another class is called subclass.
• In Java, a subclass can have only one super class.
Benefits of Inheritance
• It allows the reuse of already developed and debugged class program without any
modification.
• It allows a number of subclasses to fulfil the needs of several subgroups.
• A large program may be divided into suitable classes and subclasses that may be
developed by separate teams of programmers.
Disadvantages of Inheritance
1. The tight coupling between super and subclasses increases and it becomes very difficult
to use them independently.
2. Program processing time increases as it takes more time for the control to jump
through various levels of overloaded classes.
3. When some new features are added to super and derived classes as a part of
maintenance, the changes affect both the classes.
4. When some methods are deleted in super class that is inherited by a subclass, the
33
WWW.JNTUKNOTES.COM/
methods of subclass will no longer override the super class method.
2. Process of Inheritance
• Inheritance means deriving some characteristics from something that is generic.
• In the context of Java, it implies deriving a new class from an existing old class, that is,
the super class.
• A super class describes general characteristics of a class of objects.
• A subset of these objects may have characteristics different from others.
• There are two ways of dealing with this problem.
• Either, make a separate class for the subset to include all the characteristics or, to have
another class that inherits the existing class, extend this class to include the special
characteristics.
34
WWW.JNTUKNOTES.COM/
3. Types of Inheritances
The following types of inheritances are supported by Java.
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance using interfaces
Example: SingleInheritance.java
class DemoA
{
void displayA()
{
System.out.println("Super Class Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Sub Class Method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
DemoA objA = new DemoA();
objA.displayA();
35
WWW.JNTUKNOTES.COM/
ii. Multilevel inheritance: In this type, a derived class inherits a parent
or super class; The derived class also acts as the parent class to other class.
Example: Multilevel.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class Multilevel
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
36
WWW.JNTUKNOTES.COM/
//calling class-B method
DemoB objB = new DemoB();
objB.displayB();
C:\>java Multilevel
Class-A Method
Class-B Method
Class-C Method
iii. Hierarchical inheritance: In this type, one class is inherited by many sub classes.
Example: Hierarchical.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
37
WWW.JNTUKNOTES.COM/
}
}
class Heirarchical
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
Output:
38
WWW.JNTUKNOTES.COM/
iv. Multiple inheritance: In this, a class is extending more than one class.
• Java does not support multiple inheritance.
• This implies that a class cannot extend more than one class.
• Suppose there is a method in class A. This method is overridden in class B and class C
in their own way.
• Since class C extends both the classes A and B.
• So, if class C uses the same method, then there will be ambiguity as which method is
called.
Example: Multiple.java
interface X
{
int x=10;
}
interface Y
{
int y=20;
}
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
39
WWW.JNTUKNOTES.COM/
class DemoB extends DemoA implements X,Y
{
void displayB()
{
System.out.println("Class-B Method : x+y = " +
(x+y));
}
}
class Multiple
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
}
}
Output:
C:\ >javac Multilevel.java
40
WWW.JNTUKNOTES.COM/
4. Universal Super Class : “ Object ” Class
• Object class is a special class and it is at the top of the class hierarchy tree.
• It is the parent class or super class of all in Java.
• Hence, it is called Universal super class.
• Object is at the root of the tree and every other class can be directly or indirectly
derived from the Object class.
Example:ObjectEquals.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class ObjectEquals
{
public static void main(String args[])
{
DemoA obj1 = new DemoA();
DemoA obj2 = new DemoA();
boolean test;
41
WWW.JNTUKNOTES.COM/
//Checking - if both object are equal
test = obj1.equals(obj2);
display(test);
// Object assignment
obj1=obj2;
Output:
C:\>javac ObjectEquals.java
C:\>java ObjectEquals
Both objects are different
Both objects are same
42
WWW.JNTUKNOTES.COM/
5. Inhibiting Inheritance of Class Using Final
• A class declared as final cannot be inherited further.
• Class variables or instance variables are declared as constant to make local
variables.
• When a class is inherited by other classes, its methods can be overridden.
• In order to prevent the methods from being overridden, that method can be
declared as final.
Example:FinalClass.java
final class A
{
int a;
A(int x) {a=x;}
void display()
{
System.out.println("a = "+ a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);
this.b=y;
}
void display()
{
System.out.println("b = "+ b);
}
}
class FinalClass
{
public static void main (String args[])
{
A objA= new A(10);
B objB= new B(100,200);
objA.display();
objB.display();
}
}
Output:
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final A
class B extends A
^
1 error
43
WWW.JNTUKNOTES.COM/
6. Access Control and Inheritance
• A derived class access to the members of a super class may be modified by
access specifiers.
• There are three access specifiers, that is, public, protected, and private.
• The code for specifying access is Access-specifier type member_identifier;
44
WWW.JNTUKNOTES.COM/
Example-1: DefaultAccess.java
class DemoA
{
int a;
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DefaultAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.a=100; // accessing all classes in the same package
objA.displayA();
}
}
Output:
C:\>javac DefaultAccess.java
C:\>java DefaultAccess
Class-A Method : a = 100
Class-B Method : a = 200 b = 300
45
WWW.JNTUKNOTES.COM/
Example -2: PrivateAccess.java
class DemoA
{
private int a;
DemoA(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class PrivateAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(150);
//objA.a=100; // Error, Can't access private variable
objA.displayA();
}
}
46
WWW.JNTUKNOTES.COM/
Output:
C:\>javac PrivateAccess.java
C:\>java PrivateAccess
Class-A Method : a = 150
Class-A Method : a = 500
Class-B Method : b = 1000
Example: ProtectedAccess.java
class DemoA
{
protected int a;
DemoA(int t)
{
a = t;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
47
WWW.JNTUKNOTES.COM/
}
class ProtectedAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(100);
//objA.a=100; // Error, Can't access protected variable
objA.displayA();
}
}
Output:
C:\>javac ProtectedAccess.java
C:\>java ProtectedAccess
Class-A Method : a = 100
Class-B Method : a= 200 b = 300
Class-B Method : a = 250 b = 500 c = 750
48
WWW.JNTUKNOTES.COM/
7. Multilevel Inheritance
In this type, a derived class inherits a parent or super class;
• The derived class also acts as the parent class to other class.
49
WWW.JNTUKNOTES.COM/
8. Application of Keyword Super
The keyword super is used for two purposes:
First, to distinguish between the variables having the same name in super class and
subclass.
• When the member is called with an object of subclass, the subclass value will be
presented and super class value will get hidden.
• For getting super class value, the keyword super is used.
Second, it is used in defining the constructor of subclass.
• Instead of repeating the assignment of variables of super class, we simply qualify
the variable with super.
Example: SuperDemo.java
class A
{
int a;
A(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class B extends A
{
int b;
B(int p, int q)
{
super(p); // Calling Super class Construtor
b=q;
}
void displayB()
{
// Refering Super class with super keyword
System.out.println("Class-B Method : a = " + super.a + " b = " + b );
}
}
class SuperDemo
{
public static void main(String args[])
{
//Creating class B object by calling sub class constructor
B objB = new B(500,1000);
}
}
Output:
C:\>javac SuperDemo.java
C:\>java SuperDemo
50
WWW.JNTUKNOTES.COM/
Class-B Method : a = 500 b = 1000
51
WWW.JNTUKNOTES.COM/
9. Constructor Method and Inheritance
• For getting super class value, the keyword super is used.
• Second, it is used in defining the constructor of subclass.
• Instead of repeating the assignment of variables of super class, we simply qualify
the variable with super.
• Example: SuperDemo.java
10.Method Overriding
• It is one of the ways in which polymorphism can be implemented.
• When both super class and its subclass contain a method that has the same name and type
signature, the super class definition of the method is overridden by definitions in
subclass.
• It is different from the overloaded method in which only the name is same but parameter
list has to be different either in type or in number of parameters or order of parameters.
• In the case of overloaded methods, the parameter lists are matched to choose the
appropriate method that may be in super class or subclass.
• When two methods with the same name and type signature are defined in super (base)
class as well as in subclass (derived class), the subclass definition overrides the super
class definition when the method is called by object of subclass;
• It will execute the method defined in subclass and hide the definition of super class.
Binding
• It involves associating the method call to method body. There are two types of binding as
follows:
Static binding : When the binding is performed at compile time by the compiler, it is
known as static or early binding.
• For instance, binding for all static, private, and final methods is done at the compile time.
Dynamic binding : It is also called late binding. Here, the compiler is not able to resolve the
call (or binding) at compile time.
• Method overriding is one such example where dynamic binding is involved.
• The basic difference between static and dynamic binding is that static binding occurs at
compile time, whereas dynamic binding happens at run time.
Example: MethodOverriding.java
class A
{
void display()
{
System.out.println("Super Class Method");
}
}
class B extends A
52
WWW.JNTUKNOTES.COM/
{
void display()
{
System.out.println("Sub Class Method");
}
}
class MethodOverriding
{
public static void main(String args[])
{
//calling the class A method
A objA = new A();
objA.display();
C:\>javac MethodOverriding.java
C:\>java MethodOverriding
Super Class Method
Sub Class Method
Example: MethodOverriding.java
53
WWW.JNTUKNOTES.COM/
12.Abstract Classes
The abstract keyword is a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
Example: Abstract.java
abstract class A
{
int a;
void setValue(int x)
{
a=x;
}
abstract void display();
}
class B extends A
{
int b;
void setValues(int x, int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " b = " + b);
}
}
class C extends A
{
int c;
void setValues(int x, int y)
{
a=x;
c=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " c = " + c);
}
}
54
WWW.JNTUKNOTES.COM/
class Abstract
{
public static void main(String args[])
{
//calling class-B method
System.out.println("Through objB");
B objB = new B();
objB.setValues(10,20);
objB.display();
Example: Multiple.java
55
WWW.JNTUKNOTES.COM/
III. Interfaces:
1. Introduction
• https://www.w3schools.com/java/java_interface.asp
An interface is a completely "abstract class" that is used to group related methods
with empty bodies
• https://www.javatpoint.com/interface-in-java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
• https://www.geeksforgeeks.org/interfaces-in-java/
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
• An interface also introduces a new reference type.
• An interface represents an encapsulation of constants, classes, interfaces, and one or
more abstract methods that are implemented by a class.
• An interface does not contain instance variables.
• An interface cannot implement itself; it has to be implemented by a class.
• The methods in an interface have no body.
• Only headers are declared with the parameter list that is followed by a semicolon.
• The class that implements the interface has to have full definitions of all the abstract
methods in the interface.
• An interface can be implemented by any number of classes with their own definitions
of the methods of the interface.
• Different classes can have different definitions of the same methods but the
parameter list must be identical to that in the interface.
• Thus, interfaces provide another way of dynamic polymorphic implementation of
methods.
• Any number of interfaces can be implemented by a class.
• This fulfils the need for multiple inheritance.
• The multiple inheritances of classes are not allowed in Java, and therefore, interfaces
provide a stopgap arrangement.
56
WWW.JNTUKNOTES.COM/
2. Declaration of Interface
• Declaration of an interface starts with the access modifier followed by keyword
interface.
• It is in then followed by its name or identifier that is followed by a block of
statements;
• These statements contain declarations of variables and abstract methods.
• The variables defined in interfaces are implicitly public, static, and final.
• They are initialized at the time of declaration. The methods declared in an
interface are public by default.
Members of Interface
• The members declared in the body of the interface.
• The members inherited from any super interface that it extends.
• The methods declared in the interface are implicitly public abstract member
methods.
• The field variables defined in interfaces are implicitly public, static, and final.
• However, the specification of these modifiers does not create a compile-type
error.
• The field variables declared in an interface must be initialized; otherwise,
compile-type error occurs.
• Since Java SE8, static and default methods with full definition can also be
members of interface.
57
WWW.JNTUKNOTES.COM/
3. Implementation of Interface
Declaration of class that implements an interface
4. Multiple Interfaces
• Multiple interfaces can also be implemented in Java.
• For this, the class implements all the methods declared in all the interfaces.
• When the class is declared, names of all interfaces are listed after the keyword
implements and separated by comma.
• As for example, if class A implements interfaces C and D, it is defined as
Example: Multiple.java
Interface References:
• For interface references, variables can be declared as object references.
• In this case, the object reference would use interface as the type instead of
class.
• The appropriate method is called on the basis of actual instance of the
interface that is being referred to.
58
WWW.JNTUKNOTES.COM/
Example: InterfaceRef.java
interface X
{
int x = 10;
public void display();
}
interface Y
{
int y = 20;
public void add();
}
class A implements X,Y
{
public void display()
{
System.out.println("Class-B Method : x = "+ x + " y = " + y);
}
public void add()
{
System.out.println("Class-B Method : x+y = "+ (x+y));
}
}
class InterfaceRef
{
public static void main(String args[])
{
//Reference of X
X objX = new A();
objX.display();
//Reference of Y
Y objY = new A();
objY.add();
}
}
Output:
C:\ >javac InterfaceRef.java
59
WWW.JNTUKNOTES.COM/
5. Nested Interfaces
• An interface may be declared as a member of a class or in another
• interface.
• In the capacity of a class member, it can have the attributes that are applicable to other
class members.
• In other cases, an interface can only be declared as public or with
default (no-access modifier) access.
• Syntax of nested interface in another interface is given as
60
WWW.JNTUKNOTES.COM/
Example: NestedInterface.java
interface OuterX
{
int x = 10;
public interface InnerY
{
int y = 20;
}
}
class NestedInterface
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}
}
Output:
C:\ >javac NestedInterface.java
61
WWW.JNTUKNOTES.COM/
6. Inheritance of Interfaces
Inheritance of Interfaces is similar to the Inheritance of classes. Interface can be
derived from another interface.
Syntax:
Example:
interface A{}
interface B{}
interface C extends A,B
{
//Body of the interface
}
interface X
{
int x = 10;
}
interface Y extends X
{
int y = 20;
}
class A implements Y
{
void display()
{
System.out.println("Class-A Method : x = "+ x + " y = " + y);
}
}
class InterfaceInheritance
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}
62
WWW.JNTUKNOTES.COM/
}
Output:
C:\1. JAVA\UNIT-3.3>javac InterfaceInheritance.java
63
WWW.JNTUKNOTES.COM/
Example : DefaultMethods.java
interface X
{
int x = 10;
default void display()
{
System.out.println("Method in Interface X the value x
= " + x);
}
}
class A implements X
{
class DefaultMethods
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}
}
Output:
C:\>javac DefaultMethods.java
C:\>java DefaultMethods
Method in Interface X the value x = 10
64
WWW.JNTUKNOTES.COM/
8. Static Methods in Interface
• The Java version 8 allows full definition of static methods in interfaces.
• A static method is a class method.
• For calling a static method, one does not need an object of class.
• It can simply be called with class name as
class_name.method_name()
Example: StaticMethods.java
interface X
{
int x = 10;
static void display()
{
System.out.println("Method in Interface X the value x
= " + x);
}
}
class StaticMethods
{
public static void main(String args[])
{
//calling static method by specifying interface X
X.display();
}
}
Output:
C:\>javac StaticMethods.java
C:\>java StaticMethods
Method in Interface X the value x = 10
65
WWW.JNTUKNOTES.COM/
Java Lambda Expressions
• Lambda Expressions were added in Java 8.
• A lambda expression is a short block of code which takes in parameters and returns a
value.
• Lambda expressions are similar to methods, but they do not need a name and they can
be implemented right in the body of a method.
Syntax
The simplest lambda expression contains a single parameter and an expression:
Parameter -> expression
Example1:
import java.util.ArrayList;
C:\>javac LambdaExpressions.java
C:\>java LambdaExpressions
5
9
8
1
C:\1. JAVA\UNIT-3.3>
66
WWW.JNTUKNOTES.COM/
9. Functional Interfaces
• In Java SE8, a new package java.util.function on functional interfaces has been introduced
for writing Lambda functions.
• Functional interfaces are interfaces with one abstract method.
• They are also called SAM or single abstract method type.
• However, a functional interface can have more than one static and default methods.
• The programmer may include an annotation, to lessen the work of complier.
@FunctionalInterface
• By adding the above annotation, it can be helpful in detecting compile time errors.
• If the functional interface contains more than one abstract method, the compiler will throw
an error.
Example:Funcanal.java
import java.util.function.Function;
import java.util.function.BinaryOperator;
class Functional
{
public static void main(String args[])
{
//declaring logrithm and minimum as functional interfaces
Function <Double, Double> logrithm = Math::log;
BinaryOperator<Integer> minimum = Math::min;
Output:
C:\ >javac Functional.java
67
WWW.JNTUKNOTES.COM/
Functional Consumer<T>
• The interface declaration is
@FunctionalInterface
public interface Consumer {void accept(T t);}
• It declares one abstract method void accept(T t).
• The method only consumes its argument. It does not give any return value.
Example: ConsumerDemo.java
import java.util.function.Consumer;
class ConsumerDemo
{
public static void main(String args[])
{
//declaring logrithm and minimum as functional interfaces
System.out.print("double value = ") ;
Consumer<Double> FunInt1 = (Double d) -> { display(d); };
FunInt1.accept(3.14);
class A
{
public void display()
{
System.out.println("In class A");
}
}
class B extends A
{
@Override public void display()
{
System.out.println("In class B");
}
}
class C extends A
{
@Override public void display()
{
System.out.println("In class C");
}
}
class Annotational
{
public static void main(String args[])
{
A objA = new A();
B objB = new B();
C objC = new C();
69
WWW.JNTUKNOTES.COM/
objA.display();
objB.display();
objC.display();
}
}
Output:
C:\1. JAVA\UNIT-3.3>javac Annotational.java