Inheritance

invisibleufo101·2024년 9월 14일

Java

목록 보기
9/10
post-thumbnail

What is inheritance exactly?

Inheritance allows one class (child or subclass) to use the properties and methods of its parent class (superclass). This greatly enhances code reusability and helps to avoid redundancy.

Note: : Java allows single inheritance, meaning that a class can only inherit from one parent class at a time.

Example:

public class Animal {
    void eat() {
        System.out.println("This animal eats");
    }
}

public class Dog extends Animal {
    void bark() {
        System.out.println("This dog barks");
    }
}

public class InheritanceExample {
	public static void main(String[] args){
    	Dog myDog = new Dog();
        
        myDog.eat(); // This animal eats
        myDog.bark(); // This dog barks
    }
}

In the code above, we can see that the Dog class can use both the bark() method and eat() method because it is the child of the Animal class.


Inheritance and Access Modifiers

  • public/protected members: Inherited by the child class regardless of package.
  • private members: Not inherited; they are restricted to the parent class.
  • default (package private): Accessible only if the child class is in the same package as the parent class.

Example:

public class Animal {
    private int age;  // Not inherited by child classes
    protected String breed;  // Inherited if in same package or subclass
}

public class Dog extends Animal {
    public void show() {
        // System.out.println(age); // Error. private field
        System.out.println(breed); // Works. protected field
    }
}

The super() Keyword

The super keyword is used to refer to the parent class. It can be used for:
1. Calling the parent class's constructor.
2. Accessing the parent class's methods or fields when they are overridden in the child class.

Calling Parent Constructor:

The child class can use super() to call the parent class’s constructor. It must be the first line inside the child class constructor. If super() isn't called explicitly, the compiler will assume that the parent class's no-argument constructor is being called.

public class Animal {
    String breed;
    public Animal() {
        System.out.println("Animal class constructor");
    }
    
    public Animal(String breed) {
        this.breed = breed;
    }
}

public class Dog extends Animal {
    public Dog() {
        super();  // Calls Animal's no-argument constructor
    }
    
    public Dog(String breed) {
        super(breed);  // Calls Animal's parameterized constructor
    }
}

Do We Need to Create Constructors Manually?

If a class requires specific parameters for its constructor, you need to define it manually in the child class. If not, the compiler tries to use the default no-argument constructor. Not providing an appropriate constructor when parameters are required will result in a compilation error.


Overriding Parent Class Methods

Method overriding allows the child class to provide its own implementation of a method that is already defined in the parent class. This is useful when the subclass needs to modify or extend the behavior of the parent class's method.

Rules for Overriding:

  1. Same Signature: The method in the child class must have the same method name, return type, parameter types, and parameter order as the method in the parent class.
  2. Access Modifier: You cannot reduce the visibility (i.e. lower the access level from public to default or default to private).
  3. Exception Handling: The overridden method cannot throw new or higher level exceptions than the parent class method.

Example of Overriding:

public class Animal {
    public void sound() {
        System.out.println("Animal makes a cry!");
    }
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Woof!");
    }
}

Dog overrides the sound() method from Animal. Instead of printing "Animal makes a cry!" the Dog class will print "Woof!".


Using the Parent Class Method with super

When a method is overridden, the child class’s version of the method is called by default. However, you can still access the parent class’s version of the method using super.methodName().

Example of super in Overriding:

public class Animal {
    public void eat() {
        System.out.println("Animal is eating.");
    }
}

public class Dog extends Animal {
    @Override
    public void eat() {
        super.eat();  // Calls the parent class's eat() method
        System.out.println("Dog is eating dog food.");
    }
}

Inheritance in Different Packages

When the parent and child classes are in different packages:

  • public methods and fields are still inherited.
  • protected members can be inherited only by subclasses, even if they are in different packages.
  • default (package-private) members are not inherited if the child class is in a different package.

Example:

// Parent class in package1
package package1;

public class Animal {
    protected String color;
}

// Child class in package2
package package2;
import package1.Animal;

public class Dog extends Animal {
    public void showColor() {
        System.out.println(color);  // Accessible because color is protected
    }
}
profile
하나씩 차근차근

0개의 댓글