简体   繁体   中英

Java: Why is the parent class methods visible to the derived class?

 class Base {
    public void display(int n){ 
        System.out.println(n); 
        
    }}
 class Derived extends Base{ 
    public void display(){ //Line-1 
        System.out.println("display overloaded"); 
            
        }}
public class Tester { 
    public static void main(String[] args){ 
        Derived ref = new Derived(); 
        ref.display(10); //Line-2 
                }}

Why does this code work?How is the parent class methods visible and available to the child class? Shouldn't line 2 throws an error saying that there is no such method or that the method defined shouldn't have any parameters.

Those are different methods, to override a method you must have the same method signature

@Override
public void display(int n){ 
  System.out.println("display overloaded"); 
}

Add also @Override to indicate you are overriding base method

Notice you can't really delete a method, just override it (or overload as your example)

In java all the methods and variables with public and protected access modifiers are inherited from Parent class to Child class. Due that your display method with input parameter as int display(int n) is also inherited from parent class Base to Derived . Resulting method will be available to base class as well.

And when you create display method in your Derived class with no parameter display() , you are actually using method overloading concept (not overriding). So in your Derived class, actually you have two methods with same name (different argument) display() and display(int n) .

And that's why you are not getting no such method or that the method defined shouldn't have any parameters .

派生的方法覆盖了其超类中的方法,但它没有接受任何参数,但是您向派生的子类提供了一个参数,因此它会找到哪个方法正在接受一个参数,并且它找到了,这就是它没有给出错误的原因

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