Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access specifier protected

 
Saurabh Naik
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package pack1;
class Animal
{
protected void printMe()
{
System.out.println("in Animal's printme method");
}
}

package pack2;
import pack1.Animal;

class Horse extends Animal
{
public static void main(String args[])
{
Animal a = new Animal();
a.printme();
}
}

it gives me the error for protected access specifier.
why it is so ? we can access data from different package with protected by extending class.. ???
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
horse inherits animal members. if you wish to access these members in horse then you do so by inheritance only i.e this.printMe() [or anotherHorseReference.printMe()]. you cannot access them using animal reference i.e they way you did.
[ August 01, 2008: Message edited by: Milan Sutaria ]
 
Mike Mitchell
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do so, but it must be from a child reference. class Animal need also be public.

 
Sandeep Bhandari
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mike Mitchell:
class Animal need also be public.


That's what came to my mind before seeing that the method is protected.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic