tin_tin
tin_tin

Reputation: 488

What is difference in the following two programs?

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 the reason for this error??

Upvotes: 0

Views: 86

Answers (4)

Alexandr
Alexandr

Reputation: 9515

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();
}

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308269

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!

Upvotes: 4

reef
reef

Reputation: 1833

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

Upvotes: 0

Suraj Chandran
Suraj Chandran

Reputation: 24801

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.

Upvotes: 1

Related Questions