1 of 33 30-12-2024, 11:29
•
•
•
•
access_modifierclass<class_name>
{
data member; method;
constructor; nested
class; interface;
}
Example1
//datamember(alsoinstancevariable)
Stringname;
//JavaProgramforclassexample
publicstaticvoidmain(Stringargs[])
classStudent{
{
//datamember(alsoinstancevariable)
intid;
2 of 33 30-12-2024, 11:29
//creatinganobjectof
//Student
Student s1 = new Student(); System.out.println(s1.id); System.out.println(s1.name);
}
}
0
null
0
null
GeeksForGeeks
GeeksForGeeks
3 of 33 30-12-2024, 11:29
4 of 33 30-12-2024, 11:29
5 of 33 30-12-2024, 11:29
6 of 33 30-12-2024, 11:29
7 of 33 30-12-2024, 11:29
8 of 33 30-12-2024, 11:29
Dogtuffy;
1
2
3
4
5
Java 6
7
8
9 //ClassDeclaration
1
0
publicclassDog{
1 // Instance Variables String name;
12
Stringbreed;
13 int {age; String color;
14 this.name=name;
15 this.breed=breed;
9 of 33 //ConstructorDeclarationofClass 30-12-2024, 11:29
10 of 30-12-2024, 11:29
16 this.age=age;
17 this.color=color;
18 }
19
20
//method1
21
publicStringgetName(){returnname;}
22
23
//method2
24
publicStringgetBreed(){returnbreed;}
25
26
//method3
27
publicintgetAge(){returnage;}
28
29
//method4
30
publicStringgetColor(){returncolor;}
31
32
@OverridepublicStringtoString()
33
{
34
return("Himynameis"+this.getName()
35 +".\nMybreed,ageandcolorare"
36 + this.getBreed() + ","+
this.getAge()
37 +","+this.getColor());
38 }
39
40
publicstaticvoidmain(String[]args)
41
{
42
Dogtuffy
43 = new Dog("tuffy", "papillon", 5, "white");
44 System.out.println(tuffy.toString());
45 }
Himynameistuffy.
Mybreed,ageandcolorarepapillon,5,white
11 of 30-12-2024, 11:29
Java
1 publicclassGFG{
2 //sw=software
3
4
static String sw_name; staticfloatsw_price;
5
6
7
8
9 staticvoidset(Stringn,floatp)
10 {
11
sw_name = n; sw_price = p;
12
13 }
14
staticvoidget()
{
System.out.println("Software name is: "+ sw_name);
System.out.println("Softwarepriceis:"
+sw_price);
15 }
16
17
18
19
20
21 publicstaticvoidmain(Stringargs[])
22
23 {
GFG.set("Visual studio", 0.0f); GFG.get();
}
Software name is: Visual studio Software price
is: 0.0
12 of 30-12-2024, 11:29
Dogtuffy=newDog("tuffy","papillon",5,"white");
13 of 33
14 of 33
// creating object of class Test Test t = new
Test();
//creatingobjectofpublicclassTest
//considerclassTestpresentincom.p1package
Testobj=(Test)Class.forName("com.p1.Test").newInstance();
15 of 33
// creating object of class Test Test t1 = new
Test();
// creating clone of above object Test t2 =
(Test)t1.clone();
16 of 33
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file); Object obj =
in.readObject();
Test test = new Test(); test = new
Test();
classAnimal{}
class Dog extends Animal {} class
Cat extends Animal {} public class
Test
17 of 33
{
// using Dog object Animal obj
= new Dog();
//usingCatobject
18 of 33
•
•
•
btn.setOnAction(newEventHandler()
{
publicvoidhandle(ActionEventevent)
{
System.out.println("HelloWorld!");
}
});
19 of 33
20 of 33
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by
which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means
creating new classes based on existing ones. A class that inherits from another class can reuse the methods and
fields of that class. In addition, you can add new fields and methods to your current class as well.
Why Do We Need Java Inheritance?
Inheritance is a key feature of OOP, allowing you to create flexible and reusable code. Understanding how to
implement it effectively can greatly improve the structure of your programs. The Java Programming Course
provides real-world examples to help you see how inheritance plays out in large-scale Java applications.
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.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and common properties/ attributes.
Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class or a
parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there
is already a class that includes some of the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
21 of 33
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 DerivedClass extends BaseClass
{
//methods and fields
}
Inheritance in Java Example
Example: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class
that extends the Bicycle class and class Test is a driver class to run the program.
Try it on GfG Practice
redirect icon
// Java program to illustrate the
// concept of inheritance
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
this.gear = gear;
this.speed = speed;
// the Bicycle class has three methods
public void applyBrake(int decrement)
speed -= decrement;
22 of 33
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}
// derived class
class MountainBike extends Bicycle {
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
23 of 33
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}
// driver class
public class Test {
public static void main(String args[])
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Output
No of gears are 3
speed of bicycle is 100
seat height is 25
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a
single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and
‘B’ is a child class. The class ‘B’ inherits all the properties of the class ‘A’.
Single inheritance
24 of 33
Single inheritance
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
class Two extends One {
public void print_for() { System.out.println("for"); }
}
// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as
the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
Multilevel Inheritance
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;
25 of 33
// Parent class One
class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}
// Child class Two inherits from class One
class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
// Child class Three inherits from class Two
class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
26 of 33
System.out.println("Geeks");
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();
// Calling method from class Two
27 of 33
g.print_for();
// Calling method from class Three
g.print_lastgeek();
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below
image, class A serves as a base class for the derived classes B, C, and D.
Hierarchical-Inheritance-in-Java
// Java program to illustrate the
// concept of Hierarchical inheritance
class A {
public void print_A() { System.out.println("Class A"); }
class B extends A {
28 of 33
public void print_B() { System.out.println("Class B"); }
class C extends A {
public void print_C() { System.out.println("Class C"); }
class D extends A {
public void print_D() { System.out.println("Class D"); }
// Driver Class
public class Test {
public static void main(String[] args)
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
29 of 33
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes.
Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B.
Multiple Inheritance
Multiple Inheritance
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
interface One {
30 of 33
public void print_geek();
interface Two {
public void print_for();
interface Three extends One, Two {
public void print_geek();
class Child implements Three {
@Override public void print_geek()
System.out.println("Geeks");
public void print_for() { System.out.println("for"); }
// Drived class
public class Main {
public static void main(String[] args)
31 of 33
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances with
classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid
inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use of Multiple Inheritance
exclusively. It can be achieved through a combination of Multilevel Inheritance and Hierarchical Inheritance with
classes, Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible to implement Hybrid
inheritance using classes alone, without relying on multiple inheritance type.
32 of 33
33 of 33