我需要制作一个项目,该项目具有使用 Java 的面向对象编程的所列特征。
有人可以查看我的快速示例程序以确认我了解这些特性是如何实现的,并且它们都存在并且正确完成了吗?
package Example;
public class Parent {
private int a;
public void setVal(int x){
a = x;
}
public void getVal(){
System.out.println("value is "+a);
}
}
public class Child extends Parent{
//private fields indicate encapsulation
private int b;
//Child inherits int a and getVal/setVal methods from Parent
public void setVal2(int y){
b = y;
}
public void getVal2(){
System.out.println("value 2 is "+b);
}
//having a method with the same name doing different things
//for different parameter types indicates overloading,
//which is an example of polymorphism
public void setVal2(String s){
System.out.println("setVal should take an integer.");
}
}
最佳答案
您的多态性 示例仅仅是方法重载,而这实际上并不是面向对象人员所说的多态性。它们意味着您如何拥有一个公开方法的接口(interface),以及实现该 interface
的各种 classes
可以实现该方法以具有不同的行为。
参见 this .特别是介绍的最后一段。
此外,我建议在代码中展示多态性知识的最佳方式必然包括一些使用多态对象的客户端代码,以展示它们可以具有不同的行为,即 poly 行为。
关于以封装、多态和继承为特色的 Java 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14739586/