[Java] Muscle Java Object Oriented Day 2 ~Inheritance~

1 minute read

What is inheritance?

  • Inherit the definition contents of the class -Can be used as is without redefining method fields: convenient

Inheritance in Java

  • Extend: Add your own methods and fields in inherited class (child class)
  • Redefinition (override): You can change the original method field definition in the inherited class (child class)

Image of inheritance

  • Children are stronger than parents -Kame Sennin (parent class) and disciple Goku (child class) -Disciple Goku Kamehameha (you can use the parent’s definition as it is) + Triple Kamehameha (override) + Maikujutsu (expansion)

Inheritance terms

  • Original class (inherited class) -Parent class -Super class -Inheritor

  • Class that inherits the original class -Child class -Subclass -Derived class -Inherited class -Inheritance destination

Inheritance code example: How to define

  • extends keyword
  • Can be used in child class without writing fields and methods of parent class
  • You can specify only one parent class
class child class name extends parent class name {

}

Inheritance code example

  • Parent class
public class Animal{
  public void eat(String f){
    System.out.println(f+"eat" ");
  }
  public void sleep(){
    System.out.println("sleeps");
  }
  public void wakeUp(){
    System.out.println("wakes up");
  }
}
  • Child class -Bird class can call sleep method and wakeUp method of parent Animal class -①: Expansion -②: Override
public class Bird extends Animal{
  
  // ①: Expansion
  public static int wing = 2;
  pulic void fly(){
    System.out.println("fly");
  }

  // ②: Override
    // Same method name as parent
  pulic void sleep(){
    System.out.println("sleeps on a tree");
  }
}

“super” keyword

  • Can use parent class definition when overriding
  • Used when you want to access the method or field of the parent class from the overridden method of the child class
public class Bird extends Animal{

  pulic void sleep(){
    System.out.println("sleeps on a tree");
    
    // super
    super.sleep();
}