具有封装、多态和继承的 Java 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14739586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:13:01  来源:igfitidea点击:

Java example featuring encapsulation, polymorphism, and inheritance?

javainheritancepolymorphismencapsulation

提问by user2048643

I need to produce a project featuring the listed characteristics of object oriented programming using Java.

我需要制作一个项目,该项目具有使用 Java 的面向对象编程的所列特征。

Could someone look over my quick sample program to confirm that I understand how these characteristics are implemented and that they are all present and done correctly?

有人可以查看我的快速示例程序以确认我了解这些特性是如何实现的,并且它们都存在并正确完成吗?

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.");
    }
}

采纳答案by chad

Your polymorphismexample is merely method overloadingand that's not actually what the Object Oriented folks mean by polymorphism. They mean how you can have a interface that exposes a method, and the various classesthat implement that interfacecan implement the method to have different behaviors.

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

See this. Last paragraph of the introduction in particular.

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

Also, I would suggest that the best way to demonstrate knowledge of polymorhpism in code would necessarily include some client code that uses the polymorphic objects to demonstrate that they can have different, i.e. poly, behaviors.

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

回答by whiskeyspider

A couple of things:

几件事:

  • Getter method should return values.
  • Overloading is different from overriding. You probably want to override setVal() (or maybe some other more appropriate method) in your child class in order to demonstrate polymorphism.
  • Getter 方法应该返回值。
  • 重载与覆盖不同。您可能希望在您的子类中覆盖 setVal()(或者可能是其他一些更合适的方法)以演示多态性。


See the below example. Parent implements fooMethod(). Parent then overloads fooMethod() by adding fooMethod(String str). Think of these as two separate, completely unrelated methods -- they just happen to have very similar looking names. Overloading doesn't have anything to do with polymorphism.

请参阅以下示例。父级实现 fooMethod()。然后父级通过添加 fooMethod(String str) 重载 fooMethod()。将它们视为两个独立的、完全不相关的方法——它们只是碰巧具有非常相似的名称。重载与多态性无关。

Then Child extends Parent. Child initially inherits fooMethod from Parent, but it wants different functionality when fooMethod() is called. So Child overrides fooMethod() with its own implementation. Now when an object of Child calls fooMethod(), the Child version of fooMethod() will run, printing "bar", not "foo".

然后 Child 扩展 Parent。Child 最初从 Parent 继承 fooMethod,但在调用 fooMethod() 时它需要不同的功能。所以 Child 用它自己的实现覆盖了 fooMethod()。现在,当 Child 的对象调用 fooMethod() 时,fooMethod() 的 Child 版本将运行,打印“bar”,而不是“foo”。

public class Parent {
  public void fooMethod() {
    System.out.println("foo");
  }

  public void fooMethod(String str) {  // overloading Parent.fooMethod()
    System.out.println("foo " + str);
  }
}


public class Child extends Parent {
  public void fooMethod() {
    System.out.println("bar");  // overriding Parent.fooMethod()
  }
}

回答by Nisha

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Parent_1
{
    private int i;//encap
    private int j;

    public  void display() {            
        System.out.println("these are the 2 answer");
    }
}

class child extends Parent_1   //inher
{
    public void display()  //method overiding
    {
        System.out.println("this is for method overriding");
    }

    public void mul(int i, int j)
    {
        int k=i*j;
        System.out.println("mul of 2 int val is:"+k);
    }

    public void mul(double i,double j)  //poly
    {
         double z=i*j;
         System.out.println("mul val of 2 double is:"+z);
    }
}

class Son
{
    public static void main(String args[])
    {
         Parent_1 p=new Parent_1();

         Parent_1 pt=new child();
         child cd=new child();
         p.display();
         cd.mul(2, 20);
         cd.mul(2.2, 1.1);
         pt.display();
    }
}

回答by Oren

your example of overriding is incorrect (as in, does not demonstrate polymorphism).

您的覆盖示例不正确(例如,未演示多态性)。

you show two functions with different signatures (the types of the arguments are part of the function signature). just because they have the same name does not make them an example of overriding.

你展示了两个具有不同签名的函数(参数的类型是函数签名的一部分)。仅仅因为它们具有相同的名称并不使它们成为覆盖的示例。

overriding would be if class child had something like

最重要的是,如果班级孩子有类似的东西

public void setVal(int x){
    a = x+10;
}

which would override the setVal(int) method in its super (parent) class.

这将覆盖其超(父)类中的 setVal(int) 方法。

however a better way to demonstrate polymorphism would be something along the lines of

然而,证明多态性的更好方法是

Parent guy = new Child();
guy.getVal();