Why should I reference the base class when I can access all the methods just as well by referencing the subclass?

后端 未结 6 1714
后悔当初
后悔当初 2021-01-20 14:32

I am learning java concepts. I got a doubt in java inheritance concept. In inheritance we can assign subclass instance to a base class reference and with that we can access

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 15:26

    What you've described is the essence of polymorphism. It's a word from the Greek that means "many forms".

    If I gave you a simple hierarchy like this, you can see how the test code can get different calculation implementations out of each object without concerning itself about what kind of Shape it was dealing with:

    public interface Shape
    {
        double calculateArea();
    }
    
    class Circle implements Shape
    {
        private double radius;
    
        Circle(double r) { this.radius = r; }
    
        public double calculateArea() { return Math.PI*radius*radius; }
    }
    
    class Square implements Shape
    {
        private double side;
    
        Square(double s) { this.side = s; }
    
        public double calculateArea() { return side*side; }
    }
    
    // This would be a separate JUnit or TestNG annotated test.
    public class ShapeTest
    {
        @Test
        public void testCalculateArea()
        {
            Map expected = new HashMap()
            {{
                put(new Circle(1.0), Math.PI);
                put(new Square(1.0), 1.0);            
            }};
    
    
            for (Shape shape : expected.keySet())
            {
                Assert.assertEquals(expected.get(shape), shape.calculateArea());
            }       
        }
    }
    

提交回复
热议问题