-1

Why i cant call protectedMethod() even the object of class Parent call its method?

package packageA;

public class Parent{
  protected void protectedMethod(){
     System.out.println("Hello Parent");
  }
}

and in another Package :

package packageB;
import packageA.Parent;

Public Class Child extends Parent{
    public static void main(String[] args) {
        Parent parent = new Parent();
        parent.protectedMethod(); //illegal
        Child child = new Child();
        child.protectedMethod(); // legal       
    }
}
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • 1
    http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – Brian Roach Feb 19 '13 at 04:12
  • 3
    I really don't get why people take the time to downvote someone's question and accuse them of "duplicating" other questions. Why not just take the time to address his specific concern? –  Feb 19 '13 at 04:20
  • im sorry for duplicate question . i just confused about why it cant call method itself . Thank all for reply me – user2085628 Feb 19 '13 at 04:25
  • @Decave - See [this meta question](http://meta.stackexchange.com/questions/129844/why-prevent-duplicate-questions). – nickb Feb 19 '13 at 04:29
  • this one has the answer http://stackoverflow.com/questions/1622219/why-cant-i-access-protected-java-method-even-thought-ive-extended-the-class?rq=1 – Oleg Mikheev Feb 19 '13 at 04:30
  • 1
    @Decave personnally I tell the OP the question is duplicate because the OP wants to have an answer, and the original question has an answer, that is just one click away, effectively saving everyone from the bother to answer the question (and giving up the easy points that I could win plagiarizing the original answer). I didn't downvote, nor vote for closing. – Cyrille Ka Feb 19 '13 at 19:04

1 Answers1

1

Your child class can call protectedMethod() on its own parent, not on any independent Parent object that is created.

So, super.protectedMethod() would be legal, but that does not appear to be what you need. If you want to create a Child object that calls the method on a Parent object, but not its own parent, then you will have to declare the method public.

Darius X.
  • 2,886
  • 4
  • 24
  • 51