simpleclassdemo5.java
来自「JAVA程序设计课程中各章节的程序实例。」· Java 代码 · 共 75 行
JAVA
75 行
/**
*A override program of polymorphism demonstration
* it's a simple but classical example
*2005.1.10. xhcprince
*/
class Shape
{
String name = "";
final static double pi = 3.1415926;
public void area()
{
System.out.println("Shaape class:no area defined!");
}
}
class Rectangle extends Shape
{
double length,
width;
Rectangle(double len, double wid)
{
length = len;
width = wid;
}
public void area()
{
double area = length*width;
System.out.println("Shape name: " + name);
System.out.println("Shape area: " + area);
}
}
class Circle extends Shape
{
double radius;
Circle(double r)
{
radius = r;
}
public void area()
{
double area = radius*radius*pi;
System.out.println("Shape name: " + name);
System.out.println("Shape area: " + area);
}
}
public class simpleClassDemo5
{
public static void main(String args[])
{
Shape rect = new Rectangle(3.7,4.2); //pay attention to the constructor!
Shape cirl = new Circle(1.1);
rect.name = "Rectangle";
cirl.name = "Circle";
rect.area();
cirl.area();
}
}
/**
*We create the objects of Shape (not Rectengle and Circle! pay attention here),and instantiate it with the objects
* of it's subclasses (Rectanblew andd Circle).When we call the area function,the polymorphism comes into play
* The compiler at the time of compliation does not now in advance which area() function to call,this ambiguity is
* resolved at the run time.
*/
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?