YouTip LogoYouTip

Java Inheritance

body { font-family: Arial, sans-serif; line-height: 1.6; margin: 20px; } h1, h2, h3 { color: #333; } pre { background-color: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; } code { font-family: 'Courier New', monospace; } img { max-width: 100%; height: auto; } a { color: #0066cc; text-decoration: none; } a:hover { text-decoration: underline; } ul { list-style-type: disc; padding-left: 20px; } .note { background-color: #fff3cd; border: 1px solid #ffeeba; padding: 10px; border-radius: 5px; margin: 10px 0; }

Java Inheritance | Tutorial

Tutorial -- Learning more than just technology, but dreams!

Java Tutorial

Java Tutorial Java Introduction Java Development Environment Setup Java Basic Syntax Java Comments Java Objects and Classes Java Basic Data Types Java Variable Types Java Variable Naming Rules Java Modifier Types Java Operators Java Loop Structures – for, while and do…while Java Conditional Statements – if…else Java switch case Statement Java Number & Math Classes Java Character Class Java String Class Java StringBuffer and StringBuilder Classes Java Arrays Java Date and Time Java Regular Expressions Java Methods Java Constructors Java Stream, File and IO Java Scanner Class Java Exception Handling

Java Object-Oriented Programming

Java Inheritance Java Override/Overload Java Polymorphism Java Abstract Classes Java Encapsulation Java Interfaces Java Enums Java Packages Java Reflection

Java Advanced Tutorial

Java Data Structures Java Collections Framework Java ArrayList Java LinkedList Java HashSet Java HashMap Java Iterator Java Object Java NIO Files Java Generics Java Serialization Java Networking Java Sending Email Java Multithreading Java Applet Basics Java Documentation Comments Java Examples Java 8 New Features Java MySQL Connection Java 9 New Features Java Quiz Java Common Libraries

Java Exception Handling

Java Override/Overload

Java Inheritance


The Concept of Inheritance

Inheritance is a cornerstone of Java's object-oriented programming technology because it allows the creation of hierarchical classes.

Inheritance is when a subclass inherits the characteristics and behaviors of a superclass, enabling the subclass object (instance) to have the instance fields and methods of the superclass, or the subclass inherits methods from the superclass, giving the subclass the same behaviors as the superclass.

Inheritance in Real Life:

Inheritance Diagram

Rabbits and sheep belong to the herbivore class, while lions and leopards belong to the carnivore class.

Herbivores and carnivores both belong to the animal class.

Therefore, inheritance must adhere to an "is-a" relationship, where the superclass is more general and the subclass is more specific.

Although herbivores and carnivores are both animals, they differ in attributes and behaviors. Thus, a subclass will have the general characteristics of the superclass as well as its own specific characteristics.

Class Inheritance Format

In Java, you can declare that a class inherits from another class using the extends keyword. The general form is:

class SuperClass { }
class SubClass extends SuperClass { }

Why Do We Need Inheritance?

Let's illustrate this need with an example.

Develop an Animal class, where the animals are a Penguin and a Mouse, with the following requirements:

  • Penguin: Attributes (name, id), Methods (eat, sleep, introduction)
  • Mouse: Attributes (name, id), Methods (eat, sleep, introduction)

Penguin Class:

public class Penguin {
    private String name;
    private int id;

    public Penguin(String myName, int myid) {
        name = myName;
        id = myid;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }

    public void introduction() {
        System.out.println("Hello! I am " + name + ", number " + id + ".");
    }
}

Mouse Class:

public class Mouse {
    private String name;
    private int id;

    public Mouse(String myName, int myid) {
        name = myName;
        id = myid;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }

    public void introduction() {
        System.out.println("Hello! I am " + name + ", number " + id + ".");
    }
}

From these two code snippets, we can see that there is code duplication, leading to a large and bloated codebase with low maintainability (mainly because later modifications require changing a lot of code, which is error-prone). To fundamentally solve the problem in these two code segments, inheritance is needed. Extract the common parts from both segments to form a superclass:

Common Superclass:

public class Animal {
    private String name;
    private int id;

    public Animal(String myName, int myid) {
        name = myName;
        id = myid;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }

    public void introduction() {
        System.out.println("Hello! I am " + name + ", number " + id + ".");
    }
}

This Animal class can serve as a superclass. After the Penguin and Mouse classes inherit this class, they will have the attributes and methods of the superclass. The subclasses will no longer have duplicate code, maintainability is improved, the code becomes more concise, and code reusability is enhanced (reusability mainly means it can be used multiple times without writing the same code repeatedly). Code after inheritance:

Penguin Class:

public class Penguin extends Animal {
    public Penguin(String myName, int myid) {
        super(myName, myid);
    }
}

Mouse Class:

public class Mouse extends Animal {
    public Mouse(String myName, int myid) {
        super(myName, myid);
    }
}

Inheritance Types

Note that Java does not support multiple inheritance, but it supports multilevel inheritance.

Inheritance Types Diagram


Characteristics of Inheritance

  • A subclass inherits the non-private attributes and methods of the superclass.
  • A subclass can have its own attributes and methods, meaning it can extend the superclass.
  • A subclass can implement the methods of the superclass in its own way.
  • Java inheritance is single inheritance, but it supports multilevel inheritance. Single inheritance means a subclass can only inherit from one superclass. Multilevel inheritance means, for example, class B inherits from class A, and class C inherits from class B. Therefore, class B is the superclass of class C, and class A is the superclass of class B. This is a characteristic that distinguishes Java inheritance from C++ inheritance.
  • It increases the coupling between classes (a disadvantage of inheritance; high coupling means the code is more tightly connected, reducing code independence).

Inheritance Keywords

Inheritance can be implemented using the extends and implements keywords. Moreover, all classes inherit from java.lang.Object. When a class does not use either of these two keywords, it implicitly inherits from the Object class (which is in the java.lang package, so no import is needed).

The extends Keyword

In Java, class inheritance is single inheritance, meaning a subclass can only have one superclass. Therefore, extends can only inherit from one class.

public class Animal {
    private String name;
    private int id;

    public Animal(String myName, int myid) {
        // Initialize attribute values
    }

    public void eat() {
        // Implementation of the eat method
    }

    public void sleep() {
        // Implementation of the sleep method
    }
}

public class Penguin extends Animal {
}

The implements Keyword

Using the implements keyword can indirectly give Java multiple inheritance capabilities. It is used in the context of a class inheriting interfaces, allowing a class to inherit from multiple interfaces (interfaces are separated by commas).

public interface A {
    public void eat();
    public void sleep();
}

public interface B {
    public void show();
}

public class C implements A, B {
}

The super and this Keywords

super keyword: We can use the super keyword to access members of the superclass, referring to the parent of the current object.

this keyword: Refers to the current object, i.e., the instance of the object to which the method or constructor belongs.

class Animal {
    void eat() {
        System.out.println("animal : eat");
    }
}

class Dog extends Animal {
    void eat() {
        System.out.println("dog : eat");
    }

    void eatTest() {
        this.eat(); // this calls its own method
        super.eat(); // super calls the superclass method
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Dog d = new Dog();
        d.eatTest();
    }
}

Output:

animal : eat
dog : eat
animal : eat

The final Keyword

final can be used to modify variables (including class attributes, object attributes, local variables, and parameters), methods (including class methods and object methods), and classes.

final means "final".

Using the final keyword to declare a class makes it a final class that cannot be inherited. When used to modify a method, that method cannot be overridden by subclasses:

  • Declare a class:
    final class ClassName {
        // Class body
    }
  • Declare a method:
    Modifier (public/private/default/protected) final ReturnType methodName() {
        // Method body
    }

Note: For a class declared with final, its attributes and methods are not automatically final.


Constructors

A subclass does not inherit the constructors (constructor methods or constructor functions) of its superclass; it only calls them (implicitly or explicitly). If the superclass constructor has parameters, the subclass constructor must explicitly call the superclass constructor using the super keyword with an appropriate parameter list.

If the superclass constructor has no parameters, the subclass constructor does not need to use the super keyword to call the superclass constructor; the system will automatically call the superclass's no-argument constructor.

class SuperClass {
    private int n;

    // No-argument constructor
    public SuperClass() {
        System.out.println("SuperClass()");
    }

    // Constructor with parameters
    public SuperClass(int n) {
        System.out.println("SuperClass(int n)");
        this.n = n;
    }
}

// SubClass inherits
class SubClass extends SuperClass {
    private int n;

    // No-argument constructor, automatically calls the superclass's no-argument constructor
    public SubClass() {
        System.out.println("SubClass()");
    }

    // Constructor with parameters, calls the superclass constructor with parameters
    public SubClass(int n) {
        super(300);
        System.out.println("SubClass(int n): " + n);
        this.n = n;
    }
}

// SubClass2 inherits
class SubClass2 extends SuperClass {
    private int n;

    // No-argument constructor, calls the superclass constructor with parameters
    public SubClass2() {
        super(300);
        System.out.println("SubClass2()");
    }

    // Constructor with parameters, automatically calls the superclass's no-argument constructor
    public SubClass2(int n) {
        System.out.println("SubClass2(int n): " + n);
        this.n = n;
    }
}
← Java Override OverloadJava Filewriter β†’