[Java] Inheritance

What is inheritance?

How to use inheritance

Person.java


public class Person {
  public String name;
  public int age;

  public String show() {
    return String.format("%s(%d).", this.name, this.age);
  }
}

BusinessPerson.java


//Create BusinessPerson class that inherits Person
public class BusinessPerson extends Person {
  //Work method definition unique to derived class
  public String work() {
    return String.format("%d year old%s works fine today as well.", this.age, this.name);
  }
}
public class InheritBasic {
  public static void main(String[] args) {
    //Call only Business Person
    var bp = new BusinessPerson();
    bp.name = "Ichiro Sato";
    bp.age = 30;
    //The show method can be called like a member of the bp class!
    System.out.println(bp.show()); //I'm Ichiro Sato (30 years old).
    System.out.println(bp.work());  //Ichiro Sato, 30 years old, works well today.
  }
}

Field concealment

hiding

Person.java


import java.time.ZonedDateTime;
public class Person {
  public String name;
  public ZonedDateTime birth = ZonedDateTime.now();
}

BusinessPerson.java


import java.time.LocalDateTime;
public class BusinessPerson extends Person {
  //Hide the birth field of the base class
  public LocalDateTime birth = LocalDateTime.now();
  public void show() {
    //Access hidden fields
    System.out.println(super.birth);
  }
}
public class HideBasic {

  public static void main(String[] args) {
    var bp = new BusinessPerson();
    //BusinessPerson.Show birth
    System.out.println(bp.birth); 
    bp.show();
    //Person.Show birth field
    Person p = new BusinessPerson();
    System.out.println(p.birth);
  }
}

Method override

public class Person {
  public String name;
  public int age;

  public String show() {
    return String.format("%s(%d).", this.name, this.age);
  }
}
public class BusinessPerson extends Person {
  public BusinessPerson() {}
  //Override the show method with the same name in the base class
  @Override
  public String show() {
    return String.format("Of an office worker%s(%d).", this.name, this.age);
  }

  public String work() {
    return String.format("%d year old%s works fine today as well.", this.age, this.name);
  }
}

Base class reference (super)

//Inherit BusinessPerson class
public class EliteBusinessPerson extends BusinessPerson {
  @Override 
  //Call the work method of the base class and add your own processing

  public String work() {
    //Call the super method at the beginning of the derived class
    var result = super.work();
    return String.format("%s Always smile!", result);
  }
}
public class InheritBaseCall {
  public static void main(String[] args) {
    var ebp = new EliteBusinessPerson();
    ebp.name = "Yamada Taro";
    ebp.age = 35;
    System.out.println(ebp.work()); //35-year-old Taro Yamada works well today. Always smile!
  }
}

Derived class constructor

MyParent.java


public class MyParent {
  public MyParent() {
    System.out.println("I'm a parent.");
  }
}

MyChild.java


public class MyChild extends MyParent {
  public MyChild() {
    System.out.println("I'm a child.");
  }
}
public class InheritConstruct {
  public static void main(String[] args) {
    var c = new MyChild(); //I'm a parent. I'm a child.
  }
}
//Upper class (constructor with arguments)
public class MyParent {
  public MyParent(String name) {
    System.out.printf("%The parent of s.\n", name);
  }
}
public class MyChild extends MyParent {
  public MyChild(String name) {
    //Call the no-argument constructor of the upper class from the constructor of the derived class
    super(name);
    //Constructors are called in the order of base class → derived class
    System.out.printf("Of child%s.\n", name); //I'm Taro Yamada's parent.\n I'm a child of Taro Yamada.
  }
}
public class InheritConstruct {
  public static void main(String[] args) {
    var c = new MyChild("Yamada Taro");
  }
}

Inheritance / override prohibited

public class Person {
  String name;
  int age;
  public Person() {}
  //Do not override show method
  public final String show() {
    return String.format("%s(%d).", this.name, this.age);
  }
}
//No inheritance of BusinessPerson class
public final class BusinessPerson extends Person {
  public String intro() {
    return "I'm an office worker.";
  }
}

Reference type type conversion

Upcast

//Upcast
public class CastUp {
  public static void main(String[] args) {
    //Convert by assigning a BusinessPerson object to a variable of base class Person type
    Person bp = new BusinessPerson();
    bp.name = "Yamada Taro";
    bp.age = 20;
    System.out.println(bp.show());
  }
}

Downcast

Variable type / object type

BusinessPerson.java


public class BusinessPerson extends Person {
  public BusinessPerson() {}

  @Override
  public String show() {
    return String.format("Of an office worker%s(%d).", this.name, this.age);
  }

  public String work() {
    return String.format("%d year old%s works.", this.age, this.name);
  }
}
public class TypeDifference {

  public static void main(String[] args) {
    Person p = new BusinessPerson();
    p.name = "Yamada Taro";
    p.age = 30;
    // System.out.println(p.work()); //error
    System.out.println(p.show()); //I'm Taro Yamada (30 years old), an office worker.
  }
}

Hiding class methods / fields

public class HideBasic {
  public static void main(String[] args) {
    var bp = new BusinessPerson();
    System.out.println(bp.birth);
    bp.show();
    //Variable p is of type Person
    Person p = new BusinessPerson();
    //The birth field of the Person class is of type ZonedDateTime
    System.out.println(p.birth); //ZonedDateTime type
  }
}

Type judgment

//Type check
if(p instanceof Student){
    Student st = (Student)p;
    //Processing when casting is correct
}

Type acquisition

public class Main {
    public static void main(String[] args) {
    Person p1 = new Person();
    System.out.println(p1.getClass()); //class Person
    Person p2 = new BusinessPerson();
    System.out.println(p2.getClass()); //class BusinessPerson
  }
}

transfer

import java.util.Random;

public class Roulette extends Random {
//Roulette upper limit
private int bound;

  public Roulette(int bound) {
    this.bound = bound;
  }
  //Get the value to be the upper limit of the bound field and generate a random number
  @Override
  public int nextInt() {
    return nextInt(this.bound);
  }
  //Disables other unnecessary methods (contrary to Liskov Substitution Principle)
  @Override
  public boolean nextBoolean() {
    throw new UnsupportedOperationException();
  }

  @Override
  public long nextLong() {
    throw new UnsupportedOperationException();
  }
}
import java.util.Random;

public class RouletteClient {
  public static void main(String[] args) {
    Random rou = new Roulette(10);
    System.out.println(rou.nextBoolean()); //UnsupportedOperationException
  }
}
import java.util.Random;

public class Roulette {
  private int bound;
  //Keep the above object in the field
  private Random random = new Random();

  public Roulette(int bound) {
    this.bound = bound;
  }
  //Delegate processing as needed
  public int nextInt() {
    return this.random.nextInt(this.bound);
  }
}

Recommended Posts

[Java] Inheritance
Java inheritance
Java inheritance
java (inheritance)
[Java] Class inheritance
About java inheritance
[Java] Overload / Override / Inheritance
Inheritance
Inheritance
Summarize Java inheritance (Java Silver 8)
About inheritance (Java Silver)
Java
Java
[Java] Implicit inheritance memo
Java learning memo (inheritance)
Java starting from beginner, inheritance
[Java] What is class inheritance?
java (inheritance of is-a principle)
Java learning (0)
Studying Java ―― 3
[Java] array
Muscle Java Object Oriented Day 2 ~ Inheritance ~
[Java] Annotation
[Java] Module
Java array
Java tips, tips
Java methods
Java method
java (constructor)
About inheritance
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
java (array)
Java static
Java serialization
JAVA paid
Java (set)
java shellsort
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
[Java] Overload
Java basics
Decompile Java