saurabh_naik
stranger
Reged: 08/02/07
Posts: 14
|
|
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.. ???
|
hiwa
Carpal Tunnel
Reged: 06/21/03
Posts: 7704
Loc: Japan
|
|
Your code has lots of syntax error and your intended package structure is unclear. Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html
-------------------- *stop cruelty* Annual number of euthanized cats&dogs: US 5M, JP 500K.*for our better karma*
|
hiwa
Carpal Tunnel
Reged: 06/21/03
Posts: 7704
Loc: Japan
|
|
Due to the malfunctioning of the forum software, you are redirected to see the text in: http://homepage1.nifty.com/algafield/answer.txt
-------------------- *stop cruelty* Annual number of euthanized cats&dogs: US 5M, JP 500K.*for our better karma*
|
gauravrajbehl
stranger
Reged: 08/02/08
Posts: 1
|
|
Hi Saurabh,
The syntax seems to be correct, but there are couple of problems with the code which violates the java1 principles:
1) Both the classes have different access levels i.e. default and also they are in different packages. Default access classes are invisible to each other if they have default access. In order for a class to extend another class, the parent class must be either in the same package or the parent class must be public.
2) Another problem is with the protected access specifier, protected specifier applies to inheritance i.e. child classes and anything outside the package i.e if the child class is in different package and the parent class having the protected method is in the different package, the child class cannot instantiate a parent class object as it will be invisible to the child class (just like private method) but yes, the parent class protected method will be available to the child class through inheritance, so instead of creating a new object of the parent class (which is invalid), in child class from main, call a method and access your printMe() method from there. So, two things you must do for this code to work:
1) Make your parent class public i.e. public Animal
2) Call another method from your main in child class and from that child class you can access the printMe method.
I hope this helps Thanks. Gaurav Raj Behl
|