简体   繁体   中英

why I can call parent method without super keyword?

I learn java inheritance, and this is my parent and child class

public class ParentClass {
  String name;
  final String subject = "Java";

  public ParentClass(String name) {
    this.name = name;
  }

  void intro () {
    System.out.println("Learn " + this.subject);
  }
}

class ChildClass extends ParentClass {
  ChildClass(String name) {
    super(name);
  }

  void getMethodParent() {
    intro();
    System.out.println(subject);
  }
}

my question is why i can still access method or variable from parent class without using super keyword? like method intro in getMethodParent , it should be super.intro() .

I use:

  1. jdk 17.0.1
  2. Visual studio code

You can call and access it because you have inherited it. super is only needed for when you have overriden the method, but want to access the parent's version of it, still

Java has specific rules for inheritance based on the visibility you define a method. Here you declare intro() with default or package visibility, so it is automatically available in the ChildClass . This rule is similar to how you don't have to specify this before every method call in a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM