为什么这个程序不是多态的?

时间:2017-06-12 09:03:31

标签: java

在下面的程序中,我试图通过传递参数来重载方法,但两种方法的输出是相同的

 public class A 
    {

    int a = 11;
    int b = 20;
    static int c = 0;

        public void A1(){

            c = a+b;

        }

        public void A1(int a,int b){

            c = this.a+this.b;

        }

        public static void main(String[] args){

            A a = new A();
            a.A1();// this should give 31
            System.out.print(c);
            a.A1(3,46);// this should give 49
            System.out.print(c);
        }
 }

OUTPUT:两者的输出均为31。

即使我试图超载,两者的输出也是一样的。

3 个答案:

答案 0 :(得分:3)

public void A1(int a,int b){
    c = this.a+this.b;
}

您忽略了传递给方法的参数,而是添加实例变量this.athis.b

将其更改为

public void A1(int a,int b){
    c = a+b;
}

为了添加两个参数。

答案 1 :(得分:0)

在此代码中:

public void A1(int a,int b){
    c = this.a+this.b;
}

您正在使用this前缀。这意味着您使用的是类字段,而不是参数。这里的参数将被省略。

答案 2 :(得分:0)

您使用的是关键字this

这可以得到你期望的结果。

  public void A1(int a,int b){

        c = a+b;

    }

此处int aint b会隐藏实例字段ab。通过使用this关键字,您可以获取这些隐藏的字段。

相关问题