Confusing “override a private method”

后端 未结 3 837
故里飘歌
故里飘歌 2020-12-17 16:51

I have two question on this code

public class Override {
    private void f() {
        System.out.println(\"private f()\");
    }
    public static void mai         


        
相关标签:
3条回答
  • 2020-12-17 16:52

    The override of method has three conditions.child class must has the same name and parameters and returned value as its super class.But if both of the parameter and returned value are vary,so the override is not exist!even if the two method are different method!ok!like this:

    public class Parent {
              public  int addV(int a,int b){
            int s;
            s = a + b;
            return s;
        }
    }
    
    class Child extends Parent{
        public  void  addV(){
           //do...something
        }
    }
    

    Eclipse will not talk error! because the method addV in class Child is different with the method addV in class Parent.As your instance!

    0 讨论(0)
  • Override po = new Derived();
    po.f();
    

    You are accessing Override's own method even if the object is derived because as per scope rules, the private members of class are considered first, and as its written in scope of Override it is referencing the private f, and since its private its not overriden in Derived class at all, they will only override if method signature is same.

    Derived po = new Derived();
    po.f(); 
    

    Thsi is the correct code which will call Derived's f

    0 讨论(0)
    1. The main method is inside class Override, so ofcourse it can see the private members of class Override.

    2. You are not overriding method f in class Derived, there is no polymorphism. The type of the variable po is Override, so it will take method f from class Override.

    Note that method f in class Override is not visible at all in class Derived. The method f in class Derived is a different method, that doesn't have anything to do with the method f in the superclass.

    0 讨论(0)
提交回复
热议问题