I am preparing for the SCJP exam and I need help to the following problem about access modifiers. I have 2 classes(Parent,Child) as shown below:
Now compiling Parent class is ok but compiling Child class I am getting an error saying: "other.Child is not abstract and does not override abstract method method2() in test.Parent". I can see any reason why is complaining about method2 (it has a default access and it's not visible to classes outside the package). For method1 which has protected access it would be reasonable to complain if I hadn't implement it, but with method2 it's not reasonable I think. What is the problem here?
I think you've worked half of it out for yourself. Parent.method2() isn't visible outside the package, so Child can't implement it.
But, it's got to be implemented somewhere if you have a non-abstract subclass. Otherwise, you've got a class that's not valid. What happens if the object is instantiated and then something calls that method? Not being able to see the method isn't an excuse - the compiler can't allow an instance of a class without a body for all its methods.
But, it's got to be implemented somewhere if you have a non-abstract subclass. Otherwise, you've got a class that's not valid.
Please correct me if I am wrong...
Consider that I have only this two classes. Child class is non-abstract so it has to implement all abstract methods from Parent class. Method1 has a protected access and is abstract so it's visible to Child class and must be implemented. Method2 is abstract and should be also implemented, but it has default access thus making it invisible to classes outside the package "test" like Child class. It should be illegal declaring abstract with protected access, is the same like abstract and private which are illegal.
naro pad wrote:
It should be illegal declaring abstract with protected access, is the same like abstract and private which are illegal.
Private and abstract aren't possible because the method can never be visible to a subclass, so can't be implemented by a subclass. Protected and default access don't have the same problem, so they can be used with abstract, although in the case of default access the implementation can only be within the same package.