📄 simpleclassdemo5.java
字号:
/**
*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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -