Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Inheritance

● Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
● It is an important part of OOPs (Object Oriented programming system).

● 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.

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.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Java Inheritance Example


class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

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.
class Employee
{
float salary=40000;
}
class one extends Employee
{
int bonus=10000;
public static void main(String args[])
{
one p=new one();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Single inheritance

class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class one
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Multilevel inheritance

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 one{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Hierarchical

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 one
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}

Examples
Add two numbers using inheritance
class ClassA {

int a;
int b;
int result;

public void setValue(int a, int b)


{
this.a = a;
this.b = b;
}
public void showResult()
{
System.out.println("Addition of two numbers = "+result);
}
}

class ClassB extends ClassA {

public void add()


{
result = a+b;
}
}

public class MainClass {

public static void main(String args[])


{
ClassB b = new ClassB();
b.setValue(6, 4);
b.add();
b.showResult();
}}

Simple inheritance : to add ,subtract ,multiply

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class a extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
a demo = new a();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Taking input from user

import java.util.Scanner;

class Main {
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

Q) Create a class name Teacher . Assign designation and college name as “teacher “ and “kalsekar “
respectively . Create a method in teacher class name - work . let it print the work done by teacher.
Now create another main class named PhysicsTeacher who inherits property of main class and has a
variable mainsubject which displays her main subject . Call the attributes of parent class using child class

class Teacher
{
String designation = "Teacher";
String collegeName = "KALSEKAR";

void work()
{
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher


{
String mainSubject = "Physics";
public static void main(String args[])
{
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.work();
}
}

Output:
KALSEKAR
Teacher
Physics
Teaching

Inheritance and Method Overriding


class ParentClass{
ParentClass()
{
System.out.println("Constructor of Parent");
}
void disp()
{
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample()
{
System.out.println("Constructor of Child");
}
void disp()
{
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
obj.disp();
}
}

The output is :
Constructor of Parent
Constructor of Child
Child Method
Parent Method

Constructor overloading : We have already seen constructor and parameterised constructor in unit
one . let’s see constructor overloading .

public class Student


{
int id;
String name;

Student()
{
System.out.println("this a default constructor");
}

Student(int i, String n)
{
id = i;
name = n;
}

public static void main(String[] args)


{
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

OUTPUT
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null

Parameterized Constructor values:


Student Id : 10
Student Name : David
Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

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.

Consider following example of abstract class

Example 1

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");
}
}
//In real scenario, method is called by programmer or user
class a
{
public static void main(String args[])
{
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,
getShape() method
s.draw();
}
}

Example 2

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class one{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

Output
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Interface in Java

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.

How to declare an interface?

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.

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is provided
in the A class.

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

public static void main(String args[])


{
A obj = new A();
obj.print();

}
Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.

An abstract class can extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.

An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.

Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like