Moon Light Box

Time is Money

Java - Shadow

| Comments

public class ShadowExample {
    public static void main() {
        Food mFood = new Food();
        Rice mRice = new Rice();
        
        System.out.println("mFood.price = ", mFood.price);
        System.out.println("mRice.price = ", mRice.price);
    }
    
    class Food {
        protected int price = 100;
        
        public Food() {
            System.out.println(price);
        }
    }
    
    class Rice extends Food {
        protected int price = 200; // shadow


        public Rice() {
            System.out.println(price);
        }
    }
}
Result:
mFood.price = 100
mRice.price = 200

If remove below line

protected int price = 200; // shadow

And result is

Result:
mFood.price = 100
mRice.price = 100

Comments

comments powered by Disqus