java (inheritance)

Defining a class with inheritance

Original Hero class

Hero.java


public class Hero {
  String name = "Brave";
  int hp = 100;
  //fight
  public void attack(Matango m) { 
    System.out.println(this.name + "attack!");
    m.hp -= 5;
    System.out.println("Inflicted 5 points of damage!");
  }
  //escape
  public void run() {
    System.out.println(this.name + "Escaped!");
  }
}

SuperHero class without inheritance

SuperHero.java


public class SuperHero {
  String name = "Brave";
  int hp = 100;
  boolean flying;
  //fight
  public void attack(Matango m) { 
    System.out.println(this.name + "attack!");
    m.hp -= 5;
    System.out.println("Inflicted 5 points of damage!");
  }
  //escape
  public void run() {
    System.out.println(this.name + "Escaped!");
  }
  //jump
  public void fly() {
    this.flying = true;
    System.out.println("I jumped up!");
  }
  //Land
  public void land() {
    this.flying = false;
    System.out.println("Landed!");
  }
}

Fight, run away, but overlap. If you change the Hero class, you must also change the SuperHero class.

SuperHero class with inheritance

SuperHero.java


public class SuperHero extends Hero{
  boolean flying;
  //jump
  public void fly() {
    this.flying = true;
    System.out.println("I jumped up!");
  }
  //Land
  public void land() {
     this.flying = false;
     System.out.println("Landed!");
  }
}

ʻExtend Inherit the Hero class with the original class name`.

Recommended Posts

[Java] Inheritance
Java inheritance
java (inheritance)
[Java] Class inheritance
About java inheritance
[Java] Overload / Override / Inheritance
Inheritance
Summarize Java inheritance (Java Silver 8)
About inheritance (Java Silver)
Java
Java
[Java] Implicit inheritance memo
Java learning memo (inheritance)
Advanced inheritance abstract, interface -java
JAVA learning history interface inheritance
Java starting from beginner, inheritance
[Java] What is class inheritance?
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
About inheritance
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
Java array
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