0% found this document useful (0 votes)
5 views31 pages

Unit 3

Inheritance in Java allows one class to inherit properties and behaviors from another, promoting code reusability and method overriding. Key concepts include subclasses, superclasses, and the use of the 'super' keyword to access parent class members. Additionally, abstraction can be achieved through abstract classes and interfaces, which provide a way to define methods without implementation details.

Uploaded by

newmovies1638
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)
5 views31 pages

Unit 3

Inheritance in Java allows one class to inherit properties and behaviors from another, promoting code reusability and method overriding. Key concepts include subclasses, superclasses, and the use of the 'super' keyword to access parent class members. Additionally, abstraction can be achieved through abstract classes and interfaces, which provide a way to define methods without implementation details.

Uploaded by

newmovies1638
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/ 31

Unit 3

Inheritance
Introduction
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.

Inheritance represents the IS-A relationship which is also known as a parent-child


relationship.

Why use inheritance in java

○ For Method Overriding (so runtime polymorphism can be achieved).


○ For Code Reusability.
Terms used in Inheritance
○ Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
○ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
○ Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
○ Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
Syntax
class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
Example 1
class Animal {

// methods and fields

// use of extends keyword to perform inheritance

class Dog extends Animal {

// methods and fields of Animal

// methods and fields of Dog

}
Example 2:
class Employee{
float salary=40000;
String name=”ABC”;
Void display()
{
System.out. println(“Name of employee: “+name);
}
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
p.display();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of inheritance
Types of Inheritance
Example
Programs reference Practical 4
Method overriding
If methods with the same name are defined in both superclass and subclass, the
method in the subclass overrides the method in the superclass. This is called
method overriding.
class Animal {
public void printMessage(){
// overridden method display();
public void display(){ }
System.out.println("I am an animal"); }
}
} class Main {
public static void main(String[] args) {
class Dog extends Animal { Dog dog1 = new Dog();
dog1.printMessage();
// overriding method }
@Override }
public void display(){
System.out.println("I am a dog");
}
Super keyword
The super keyword in Java is used in subclasses to access superclass members (attributes,
constructors and methods).

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Uses of super keyword

1. To call methods of the superclass that is overridden in the subclass.


2. To access attributes (fields) of the superclass if both superclass and subclass have
attributes with the same name.
3. To explicitly call superclass no-arg (default) or parameterized constructor from the
subclass constructor.
super can be used to invoke parent class method
class Animal { public void printMessage(){
// overridden method // this calls overriding method
public void display(){
display();
System.out.println("I am an animal");
// this calls overridden method
}}
super.display();
class Dog extends Animal {
}}
// overriding method
@Override class Main {

public void display(){ public static void main(String[] args) {

System.out.println("I am a dog"); Dog dog1 = new Dog();


} dog1.printMessage();

}}
super is used to refer immediate parent class instance variable.
The superclass and subclass can have attributes with the same name. We use the super keyword to access
the attribute of the superclass.

class Animal {
protected String type="animal"; class Main {
} public static void main(String[] args) {
Dog dog1 = new Dog();
class Dog extends Animal { dog1.printType();
public String type="mammal"; }
}
public void printType() {
System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}
Abstract Classes and Interfaces
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)
Abstract Classes

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
The abstract class in Java cannot be instantiated (we cannot create objects of
abstract classes). We use the abstract keyword to declare an abstract class. For
example,
// create an abstract class
An abstract class can have both the regular
methods and abstract methods. For example,
abstract class Language {
// fields and methods
}
...
// try to create an object Language
// throws an error
Language obj = new Language();
Example:

abstract class Language {

// abstract method

abstract void method1();

// regular method

void method2() {

System.out.println("This is regular method");

}
Abstract methods
A method that doesn't have its body is known as an abstract method. We use the same
abstract keyword to create abstract methods. For example,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced by ;.

If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,
// error

// class should be abstract

class Language {

// abstract method

abstract void method1();

}
Program :
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{System.out.println("running safely");}
public static void main(String args[]){
Honda4 obj = new Honda4();
obj.run();
} }
Program 2:
abstract class Shape{

abstract void draw(); }

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle");}

class Circle1 extends Shape{

void draw(){System.out.println("drawing circle");}

class TestAbstraction1{

public static void main(String args[]){

Circle c=new Circle1();

s.draw();

} }
What is an Interface?
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

It cannot be instantiated just like the abstract class.

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>{

// declare constant fields

// declare methods that abstract

// by default.

}
Relationship between classes and interfaces
Example:
interface printable{

void print();

class Demo implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

Demo obj = new Demo();

obj.print();

}
Why Multiple Inheritance is not supported in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit
properties of more than one parent class.
The problem occurs when there exist methods with the same signature in both the
superclasses and subclass.
On calling the method, the compiler cannot determine which class method to be called
and even on calling which class method gets the priority.
Consider a case where class B extends class A and Class C and both class A and C have the
same method display().
Now java compiler cannot decide, which display method it should inherit. To prevent
such situation, multiple inheritances is not allowed in java.
Program:
// Multiple Inheritance using Interface
// CNG Car interface
interface CNG_Car{ class Hybrid_Car implements Petrol_Car,
CNG_Car {
// Abstract methods
public void drive(){
void drive();
System.out.println("Driving a Hybrid Car");
void cng_kit();
}
}
// Overridden method of CNG_Car Interface
// Petrol Car interface
interface Petrol_Car{ public void cng_kit(){

// Abstract methods System.out.println("Using the CNG kit for


Hybrid Car");
void drive();
}
void petrol_kit();
}
// Overridden method of Petrol_Car Interface

public void petrol_kit(){

System.out.println("Using the Petrol kit for Hybrid Car");

}}

class MultipleInheri {

public static void main(String args[]) {

Hybrid_Car obj = new Hybrid_Car(); // Creating a new object of the Hybrid Car class

// Calling the methods of the Hybrid_Car class

obj.drive();

obj.cng_kit();

obj.petrol_kit();

}
Difference between Interface and an Abstract Class
To be done by students, any 6 points of difference.

You might also like