Java示例包含封装,多态和继承?

use*_*643 6 java polymorphism inheritance encapsulation

我需要使用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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

cha*_*had 4

您的多态性示例仅仅是方法重载,这实际上并不是面向对象的人们所说的多态性。它们意味着如何拥有一个公开方法的接口,以及如何classes实现interface可以实现该方法以具有不同行为的各种实现。

看到这个。特别是介绍的最后一段。

另外,我建议在代码中演示多态性知识的最佳方法必然包括一些使用多态对象来演示它们可以具有不同(即多态)行为的客户端代码。