What is polymorphic method in java?

后端 未结 5 1484
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 05:39

In the context of Java, please explain what a \"polymorphic method\" is.

5条回答
  •  天涯浪人
    2020-12-11 06:20

    "Polymorphic" means "many shapes." In Java, you can have a superclass with subclasses that do different things, using the same name. The traditional example is superclass Shape, with subclasses Circle, Square, and Rectangle, and method area().

    So, for example

    // note code is abbreviated, this is just for explanation
    class Shape {
        public int area();  // no implementation, this is abstract
    }
    
    class Circle {
        private int radius;
        public Circle(int r){ radius = r ; }
        public int area(){ return Math.PI*radius*radius ; }
    }
    
    class Square {
        private int wid;
        Public Square(int w){ wid=w; }
        public int area() { return wid*wid; }
    }
    

    Now consider an example

    Shape s[] = new Shape[2];
    
    s[0] = new Circle(10);
    s[1] = new Square(10);
    
    System.out.println("Area of s[0] "+s[0].area());
    System.out.println("Area of s[1] "+s[1].area());
    

    s[0].area() calls Circle.area(), s[1].area() calls Square.area() -- and thus we say that Shape and its subclasses exploit polymorphic calls to the method area.

提交回复
热议问题