java (override)

Take advantage of overrides

Hero.java


public class Hero {
  String name = "Brave";
  int hp = 100;
  //escape
  public void run() {
    System.out.println(this.name + "Escaped!");
  }
}

Redefine run () in the SuperHero class

SuperHero.java


public class SuperHero extends Hero{
  boolean flying;
  //Withdraw
  public void run() {      //It is also defined in the Hero class, but it can be redefined (overwritten)
    System.out.println(this.name + "Withdrew!");
 }
}

Call Hero and SuperHero run ()

Main.java


public class Main {
  public static void main(String[] args) {
    Hero h = new Hero();
    h.run();
    SuperHero sh = new SuperHero();
    sh.run();
  }
}

Execution result The brave escaped! The brave has withdrawn!

Prohibition of inheritance

String class and class with final when declared cannot be inherited

Main.java


public class Main extends String{

String class prohibition can also be confirmed in java API reference

Main.java


public final class Main {

Prohibition of override

Methods with final when declared cannot be overridden in child classes

Hero.java


public class Hero {
  String name = "Brave";
  int hp = 100;
  //escape
  public final void run() {     //run()Cannot be overridden
    System.out.println(this.name + "Escaped!");
  }
}

public final void run () The run () method of the SuperHero class mentioned earlier becomes invalid.

Recommended Posts

java (override)
[Java] Overload / Override / Inheritance
Java
Java
[Java] Overload and override
Java starting from beginner, override
Java learning (0)
[Java] array
Java protected
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
Java array
[Java] ArrayDeque
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 / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection
Java basics