I am creating following class hierarchy:
abstract class Shape{
protected abstract float getArea();
protected abstract float getVolume();
}
abstract class TwoDimentionalShape extends Shape{
public abstract float getArea();
protected float getVolume(){
return 0;
}
}
class Square extends TwoDimentionalShape {
float width, height;
Square(float w, float h){
width = w;
height = h;
}
public float getArea(){
return width*height;
}
}
public class ShapeTest {
public static void main(String args[]){
Shape s = new Square(3, 4);
System.out.println(s.getVolume());
}
}
What I wish to do is to hide the function getVolume() for TwoDimentionalShape class, as it will be used for ThreeDimentionalShape class.
The problem is that I have declared the function as protected, but when I call it from main(), the program is working. Why is this happening?
Protected is visible in sub classes in or outside of the package and classes in the same package. It looks like your classes are all in the same package. That is why you can see it.
In general the hierachy is:
Public – available in all packages and sub classes
Protected – avaialbe in sub classes and the same package
(Default ie nothing) available in the same package
Private – available in the same class
It is possible to access (using reflection) some fields/methods that you cannot normally “see” although this is not guaranteed and depends on teh security manager that is used.
I think the first answer of this questions explains it very well
In Java, difference between default, public, protected, and private