Java Module3 BCS306A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

MODULE 3

INHERITANCE, INTERFACES

 Inheritance is the mechanism through which we can derive classes from other classes.
 It is process of deriving features from parent class
 The derived class is called as child class or the subclass or we can say the extended class and the
class from which we are deriving the subclass is called the base class or the parent class.
 Inheritance supports code reusability: Child class can reuse the methods and fields of parent class.
 To derive a class in java the keyword extends is used.

Types of Inheritance
1. Single level/Simple Inheritance
2. Multi level Inheritance
3. Multiple Inheritance (Java doesn’t support Multiple inheritance but we can achieve this through
Interface)

Pictorial Representation of Simple and Multi level Inheritance

Single level/Simple Inheritance


 When a subclass is derived from a parent class then this mechanism is known as simple inheritance.
 In case of simple inheritance there is only a sub class and its parent class. It is also called single
inheritance or one level inheritance.
 The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
class A
{
}
class B extends A
{
}

Program to demonstrate single inheritance


class A
{
int x=10;
void get1()
{

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 1


System.out.println(“value of x is”+x);
}
}
class B extends A
{
int y=20;
void get2()
{
System.out.println(x+y);
}
}
class Main
{
public static void main(String[] args)
{
B obj=new B();
obj.get1();
obj.get2();
} }

Output:
Value of x is 10
30

Multilevel Inheritance
 When a sub class is derived from a derived class then this mechanism is known as the multi
level inheritance.
 The derived class is called the subclass or child class for it's parent class and this parent class
works as the child class for it's just above(parent) class.
 Multi level inheritance can go up to any number of level.

class A
{
int x=10;
void get1()
{
System.out.println(“value of x is”+x);
}
}
class B extends A
{
int y=20;
void get2()
{
System.out.println(x+y);
}
}
class C extends B
{
Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 2
int z=30;
void get3()
{
System.out.println(z+y);
}
}
class Main
{
public static void main(String[] args)
{
C obj=new C();
obj.get1();
obj.get2();
obj.get3();
} }
Output
Value of x is 10
30
50

super keyword
The super is java keyword. As the name suggest super is used to access the members of the
super class.
Uses of super keyword are

i. Use super with datamembers/variables


We can use super keyword to access the data member or field of immediate parent class. It
is used if parent class and child class have same fields.

class vehicle
{
int maxspeed=200;
}
class car extends vehicle
{
int maxspeed =150;
void display()
{
System.out.println(maxspeed); // 150
System.out.println(super.maxspeed); //200
}
}
class Main
{
public static void main(String[] args)
{
car obj=new car();
obj.display();

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 3


}}

ii. Use super with methods


The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class.
class A
{
void display()
{
System.out.println(“hello”);
}
}
class B extends A
{
void display()
{
super.display(); //call parent class display() hello
System.out.println(“welcome”);
}
}
class Main
{
public static void main(String[] args)
{
B obj=new B();
obj.display();
} }

iii. Use super with constructors


The super keyword can also be used to invoke the parent class constructor.

class A
{
A()
{
System.out.println(“parent class constructor”);
}
}
class B extends A
{
B()
{
super(); // call parent class constructor
System.out,println(“child class constructor”);
}
}
class Main
{
public static void main(String[] args)

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 4


{
B obj=new B();
} }
output:
Parent class constructor
Child class constructor

Method Overriding
 Method overriding in java means a subclass method overriding a super class method.
 Super class method should be non-static. Subclass uses extends keyword to extend the super class.
 If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

//Program to demonstrate method overriding


class A
{
void display()
{
System.out.println(“hello”);
}
}
class B extends A
{
void display() //method overriding
{
System.out.println(“welcome”);
}
}
class Main
{
public static void main(String[] args)
{
B obj=new B();
obj.display();
} }
output:
Welcome

 In the above program, the display() method is present in both the superclass and the subclass.
 When we call display() using the obj object (object of the subclass), the method inside the
subclass B is called. This will display welcome as output.
 If we want to access parent class display function, then use super keyword.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 5


When constructors are executed?
When a derived class is extended from the base class, the constructor of the base class is
executed first followed by the constructor of the derived class.
class A
{
A()
{
System.out.println(“parent A class constructor”);
}
}
class B extends A
{
B()
{
System.out,println(“parent B class constructor”);
}
}
class C extends B
{
C()
{
System.out,println(“child class constructor”);
}
}
class Main
{
public static void main(String[] args)
{
C obj=new C();
} }
output:
Parent A class constructor
Parent B class constructor
child class constructor

In the above program, derived class C is extended from the class B, class B is extended from
class A. When object of child class C is created the constructor of the base classes i.e A() and B() is
executed first followed by the constructor of the derived class C().

Dynamic method dispatch


 Dynamic method dispatch is the mechanism by which a calling to an overridden method will be
done at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the
object being referred to at the time the call occurs. Thus, this determination is made at run time.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 6


class mobile
{
void display()
{
System.out.println(“9 inch display”);
}
}
class Samsung extends mobile
{
void display()
{
System.out.println(“7 inch display”);
}
}
class Apple extends mobile
{
void display()
{
System.out.println(“7.5 inch display”);
}
}
class Main
{
public static void main(String args[])
{
mobile m=new mobile();
Samsung s =new Samsung();
Apple a =new Apple();
mobile ref;
ref=m;
ref.display();
ref=s;
ref.display();
ref=a;
ref.display();
}
}
Output:
9 inch display
7 inch display
7.5 inch display

The above program creates one superclass mobile and it’s two subclasses samsung and apple. These
subclasses overrides display( ) method.
1. Inside the main() method, initially objects of classes are declared.
2. Now a reference of type mobile, called ref, is also declared.
3. Now we are assigning a reference to each type of object to ref, one-by-one, and uses that reference
to invoke display( ). As the output shows, the version of display( ) executed is determined by the type
of object being referred to at the time of the call.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 7


Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
There are two ways to achieve abstraction in java
1. Abstract class
2. Interface

i. Abstract classes
A class which is declared with the abstract keyword is known as an abstract class. It can have
abstract and non-abstract methods (method with the body). It is not possible to create objects of abstract
class, its properties needs to be extended to derived class.
syntax:
abstract class A{}

 A method which is declared as abstract and does not have implementation is known as an abstract
method.
syntax:
abstract void display();//no method body and abstract

Example of Abstract class that has an abstract method


abstract class A
{
abstract void display(); // abstract method
void show() //non-abstract method
{
System.out.println(“hello”);
}
}
class B extends A
{
void display()
{
System.out.println(“Welcome”);
}
}
class main
{
public static void main(String args[])
{
B obj=new B();
obj.display();
obj.show();
}
}

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 8


In this example, A is an abstract class that contains one abstract method display() and non-abstract
method show(). As display() is an abstract method it does not have implementation part in class A. Its
implementation is provided by the class B.

Using final with inheritance


i. Using final to prevent overriding
Methods declared as final cannot be overridden.
Example:
class A
{
final void display()
{ System.out.println(“ class A”); }
}
class B extends A
{
void display() //error! cant override display() because it is declared as final in parent class
{ System.out.println(“ class A”); }
}
ii. Using final to prevent inheritance
final with class prevents a class from being inherited
Example
final class A
{
// -----
------
}
class B extends A // error! cant inherit class A
{
}

Local variable type inference and inheritance


 Type inference refers to the automatic detection of the datatype of a variable, done generally at
the compiler time.
 Local variable type inference is a feature in Java 10 that allows the developer to skip the type
declaration associated with local variables (those defined inside method definitions, initialization
blocks, for-loops, and other blocks like if-else), which is supported by the keyword ‘var’.

// Declaration of a local variable in java 10 using LVTI


class A {
public static void main(String a[])
{
var x = "Hi there";
System.out.println(x)

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 9


}
}

// Declaring iteration variables in enhanced for loops using LVTI in Java


class A {
public static void main(String a[])
{
int[] arr = new int[3];
arr = { 1, 2, 3 };
for (var x : arr)
System.out.println(x + "\n");
}
}

The object class


There is one special class, Object, defined by Java. All other classes are subclasses of Object.
That is, Object is a super class of all other classes. This means that a reference variable of type
Object can refer to an object of any other class. Also, since arrays are implemented as classes, a
variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.

Interfaces
 The interface in Java is a mechanism to achieve abstraction. There can be only variables and
abstract methods in the Java interface, not the method body.
 It is used to achieve abstraction and multiple inheritances in Java using Interface.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 10


Syntax for Java Interfaces
interface {
// declare variables
// declare abstract methods
}

 To declare an interface, use the interface keyword.


 It is used to provide total abstraction. That means all the methods in an interface are declared
with an empty body and are public and all fields are public, static, and final by default.
 A class that implements an interface must implement all the methods declared in the interface.
 To implement the interface, use the implements keyword.

// Java program to demonstrate working of interface


interface In {
int a = 10;
void display(); //public and abstract
}

// A class that implements the interface.


class A implements I {

// Implementing the capabilities of interface.


public void display()
{
System.out.println("Geek");
}

public static void main(String[] args)


{
A obj = new A();
obj.display();
System.out.println(a);
}
}

Fig: Relationship between class and interface

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 11


Accessing Implementations Through Interface References
interface In {
void display(int a);
}
class A implements In {
public void display(int p) {
System.out.println(p);
}
}

class B implements In {
public void display(int p) {
System.out.println("p squared is " + (p*p));
}
}
public class Main {
public static void main(String args[]) {
A o=new A();
B ob = new B();
In i;
i=o;
i.display(4);
i = ob;
i.display(4);
}
}
Output:
4
16

In the above program, after creating objects of class A and B, a reference variable of interface In is created.
Then Assign objects to reference variable, based on reference variable assigned methods can be accessed.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 12


Nested Interfaces
 An interface can be declared as member of a class or another interface. Such an interface is called a
member interface or a nested interface.
 While implementing the interface, we mention the interface as c_name.i_name where c_name is
the name of the class in which it is nested and i_name is the name of the interface itself.
Syntax
class abc
{
interface _interface_name {
...
}
}
// Java program to demonstrate working of interface inside a class.
class Test {
interface Yes {
void show();
}
}

class Testing implements Test.Yes {


public void show()
{
System.out.println("show method of interface");
}
}

class Main {
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj = t;
obj.show();
}
}
Output
show method of interface

Variables in Interfaces
An interface is a container of abstract methods and static final variables. The interface contains the
static final variables. The variables defined in an interface can not be modified by the class that
implements the interface, but it may use as it defined in the interface.
 The variable in an interface is public, static, and final by default.
 If any variable in an interface is defined without public, static, and final keywords then, the
compiler automatically adds the same.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 13


 No access modifier is allowed except the public for interface variables.
 Every variable of an interface must be initialized in the interface itself.
 The class that implements an interface cannot modify the interface variable, but it may use as it
defined in the interface.

Example code to illustrate variables in an interface

interface In{
int a = 100;
//int b; // Error - must be initialised
}
public class A implements In{
public static void main(String[] args)
{
System.out.println(a);
// a = 150; //Error! Can not be modified
}

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 required by the interface inheritance chain.

Following is an example:

interface A
{
void meth1();
}
interface B extends A
{
void meth2();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
}
class Main
{
public static void main(String[] args)

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 14


{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
}
}

Default Interface Methods


 Java provides a facility to create default methods inside the interface. Methods which are defined
inside the interface and tagged with default are known as default methods. These methods are
non-abstract methods.
 In the following example, In is an interface that contains a default and an abstract method. The
concept of default method is used to define a method with default implementation. We can
override default method also to provide more specific implementation for the method.
interface In
{
void display(String msg); //Abstract method
default void show () // Default method
{
System.out.println("Hello, this is default method");
}
}
class A implements in{
void display(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
A obj = new A();
obj.show(); // calling default method
obj.display("Work is worship"); // calling abstract method
}
}
Output:
Hello, this is default method
Work is worship

Use static Methods in an interface


 A static method defined by an interface can be called independently of any object. Thus, no
implementation of the interface is necessary, and no instance of the interface is required, in order
to call a static method.
 A static method is called by specifying the interface name, followed by a period, followed by the
method name.

Here is the general form:


InterfaceName.staticMethodName

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 15


interface In{
void display(String msg); // Abstract method
static void show(String msg) // static method
{
System.out.println(msg);
}
}
class A implements In{
public void display(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
A obj = new A();
obj.display("Work is worship"); // calling abstract method
In.show("Helloooo..."); // calling static method
}
}

Private Interface methods


In Java 9, we can create private methods inside an interface. Interface allows us to declare private
methods that help to share common code between non-abstract methods.

interface In{
default void say()
{
saySomething();
}
private void saySomething()
{
System.out.println("Hello... I'm private method");
}
}
class A implements In {
public static void main(String[] args) {
A obj=new A();
In ref;
ref=obj;
ref.say();
}
}
Output:
Hello... I'm private method

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 16


Questions
1. Explain the concept of inheritance and its classification.
2. Define inheritance. Explain multilevel hierarchy with an example program
3. When constructors are called in class hierarchy? Explain with an example.
4. Distinguish between method overloading and overriding in Java, with suitable example.
5. What is super? Explain the use of super with suitable example.
6. With an example, explain Dynamic method dispatch in Java.
7. Explain Local variable type inference and inheritance with example.
8. What is abstract class? Explain abstract class and abstract methods with suitable example.
9. Explain the uses of final with inheritance.
10. What is an interface? Explain how an interface can be implemented with suitable example.
11. Briefly explain the role of interfaces while implementing multiple inheritance in java.
12. Write general form of interface. Explain how interfaces can be extended with an example.
13. Briefly explain Nested interfaces with example.
14. Explain how variables in interfaces are used. Give example.
15. With an example explain static, default and private interface methods in Java.

Dept. of CSE/ISE/AIDS/AIML/CSD BGSCET, Bangalore Page 17

You might also like