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

Unit 3 Inheritance and Interface

The document provides an overview of inheritance and interfaces in Java, explaining key concepts such as subclasses, superclasses, and the types of inheritance including single, multilevel, and hierarchical. It also covers method overriding, polymorphism, the use of the 'this' keyword, and the role of interfaces and abstract classes in achieving abstraction and multiple inheritance. Additionally, it discusses wrapper classes and their importance in converting primitive types to objects.

Uploaded by

dncvpssmcbca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 3 Inheritance and Interface

The document provides an overview of inheritance and interfaces in Java, explaining key concepts such as subclasses, superclasses, and the types of inheritance including single, multilevel, and hierarchical. It also covers method overriding, polymorphism, the use of the 'this' keyword, and the role of interfaces and abstract classes in achieving abstraction and multiple inheritance. Additionally, it discusses wrapper classes and their importance in converting primitive types to objects.

Uploaded by

dncvpssmcbca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit - 3: Inheritance and Interface

Inheritance Basics:
Inheritance in Java is a concept that acquires the properties from one class to other classes; for
example, the relationship between father and son. Inheritance in Java is a process of acquiring
all the behaviours of a parent object.
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is one
of the ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you
are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example:
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...

Hierarchical Inheritance:
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark() {System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object, there
will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will be
compile time error.
Overriding in Java:
In Java, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes. When a method in a subclass has the same name, the same parameters or signature,
and the same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
Method overriding is one of the ways by which Java achieves Run Time Polymorphism. The
version of a method that is executed will be determined by the object that is used to invoke
it.
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).

// Java program to demonstrate method overriding in java


class Parent { // Base Class
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent { // // Driver class
// This method overrides show() of Parent
void show() // @Override
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers to a Child object Child's show()is called. This is
called RUN TIME POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
Output
Parent's show()
Child's show()
super Keyword in Java Overriding
A common question that arises while performing overriding in Java is:
Can we access the method of the superclass after overriding?
Well, the answer is Yes. To access the method of the superclass from the subclass, we use the
super keyword.
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
public void displayInfo() {
super.displayInfo();
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Output:
I am an animal.
I am a dog.
Explanation:
In the above example, the subclass Dog overrides the method displayInfo() of the
superclass Animal.
When we call the method displayInfo() using the d1 object of the Dog subclass, the
method inside the Dog subclass is called; the method inside the superclass is not called.
Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to call
displayInfo() of the superclass.
Polymorphism in Java:
The word "poly" means many and "morphs" means forms. So polymorphism means many
forms.
Polymorphism explores how to create and use two methods with the same name to execute
two different functionalities — like adding two functions with the same name but that accept
different parameters.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

Compile-Time Polymorphism in Java


It is also known as static polymorphism. This type of polymorphism is achieved by function
overloading or operator overloading.
Method Overloading
When there are multiple functions with the same name but different parameters then
these functions are said to be overloaded. Functions can be overloaded by changes in the
number of arguments or/and a change in the type of arguments.
Example 1:
// Java Program for Method overloading By using Different Types of Arguments
class Helper {
static int Multiply(int a, int b)
{
return a * b;
}
static double Multiply(double a, double b)
{
return a * b;
}
}
class GFG {
public static void main(String[] args)
{
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Output
8
34.65
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the
overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a derived class has a
definition for one of the member functions of the base class. That base function is said to
be overridden.
// Java Program for Method Overriding
class Parent {
void Print()
{
System.out.println("parent class");
}
}
class subclass1 extends Parent {
void Print() { System.out.println("subclass1"); }
}
class subclass2 extends Parent {
void Print()
{
System.out.println("subclass2");
}
}
class GFG {
public static void main(String[] args)
{
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Output
subclass1
subclass2
This keywords in java:
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter).
this can also be used to:
 Invoke current class constructor
 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call
public class Main {
int x;
public Main(int x) { // Constructor with a parameter
this.x = x;
}
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
Output:
Value of x = 5
Note:
1. If you omit the keyword in the example above, the output would be "0" instead of "5".
2. In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
3. If local variables(formal arguments) and instance variables are different, there is no
need to use this keyword
Interfaces in Java:
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains
static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritances in Java using Interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Abstract Classes and Methods:
 Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter).
 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).
// Abstract class
abstract class Animal {
public abstract void animalSound(); // Abstract method (does not have a body)
public void sleep() { // Regular method
System.out.println("Zzz");
}
}
class Pig extends Animal { // Subclass (inherit from Animal)
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:
The pig says: wee wee
Zzz

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
output:
running safely
Wrapper classes in Java:
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.
1. Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an
object, it will change the original value.
2. Serialization: We need to convert the objects into streams to perform the serialization. If
we have a primitive value, we can convert it in objects through the wrapper classes.
3. Synchronization: Java synchronization works with objects in Multithreading.
4. java.util package: The java.util package provides the utility classes to deal with objects.
5. Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a)
internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
20 20 20
===============================END=================================

You might also like