开发者

What is difference in the following two programs?

开发者 https://www.devze.com 2023-02-13 16:48 出处:网络
CODE:1 class Ajay { private void display() { System.out.println(\"Ajay\"); } public static void main(String ...strings ){

CODE:1

class Ajay {
    private void display() {
        System.out.println("Ajay");
    }
    public static void main(String ...strings ){
        Ajay r=new Ravi();
        r.display();
    }
}

class Ravi extends Ajay{
    public void display() {
        System.out.println("ravi");
    }
}

CODE:2

class Ravi {
    private void display() {
        System.out.println("ravi");
        }
    }

public class Ajay extends Ravi{
    public void display() {
        System.out.println("ajay");
    }
    public static void main(String ...strings ){
    Ravi r=new Ajay();
        r.display();
    }
}

I have a doubt in the above two codes. CODE 1 executes without any error while CODE 2 throws an error like The method is not visible. What is t开发者_开发百科he reason for this error??


In your second example you try to call a method display() on a variable of type Ravi. Ravi has no method display() that's accessible from this location (i.e. inside Ajay).

In your first example, however you call the private display() method of Ajay from within Ajay. Note that calling private methods does not use runtime polymorphism! The exact code to be called is decided at compile-time!


In code 2, your display method in class Ravi is private.

Now you use a reference "r" of Ravi to call display but the method display() is not visible outside the class Ravi.

Even though you have same method display() as public, in Ajay class, but its not overriding the superclass, because you can't reduce the visibility.


The error message is linked to the fact your display method in the CODE2 example is private, thus you cannot call it.


Offer solution options for the 2nd code:

if you want to display "ravi", then you may declare the display method either like:

class Ravi {
    protected void display() {
        System.out.println("ravi");
        }
    }
}

or like:

class Ravi {
    public void display() {
        System.out.println("ravi");
        }
    }
}

If you want to display "ajay", change invocation:

Ravi r=new Ajay();
    if(r instanceof Ajay)
        ((Ajay) r).display();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消