我正在观看Google Tech Talks视频,他们经常提到多态性.
什么是多态,它是什么,以及它是如何使用的?
如果我有两个班,A和B,
public class A {
public int test() {
return 1;
}
}
public class B extends A{
public int test() {
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做:A a1 = new B(),则a1.test()根据需要返回2而不是1.这只是Java的一个怪癖,还是有这种行为的原因?
interface Shape {
public double area();
}
class Circle implements Shape {
private double radius;
public Circle(double r){radius = r;}
public double area(){return Math.PI*radius*radius;}
}
class Square implements Shape {
private int wid;
public Square(int w){wid = w;}
public double area(){return wid *wid;}
}
public class Poly{
public static void main(String args[]){
Shape[] s = new Shape[2];
s[0] = new Circle(10);
s[1] = new Square(10);
System.out.println(s[0].getClass().getName());
System.out.println(s[1].getClass().getName());
}
}
Run Code Online (Sandbox Code Playgroud)
为了理解多态的概念,我发现了以下文章(/sf/answers/322404071/),但我注意到Charlie使用未实现的方法创建了Shape类.
从我的代码可以看出,我将该类转换为接口,然后使用它来实例化一个匿名类,然后调用适当的方法.
有人能告诉我我的解决方案是否合理?你会以不同的方式编写代码吗?为什么在等号的两侧使用接口的功能与它一样?
谢谢.
凯特琳