Java抽象类(这个关键字) [英] Java Abstract Class (this keyword)

查看:95
本文介绍了Java抽象类(这个关键字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我误解的东西,如果是这样,我需要帮助。

I think I'm misunderstanding something, and if so, I need help..

让我们说我有以下两类:

Let's say I have the following two classes:

public abstract class Abstraction() {
   protected int number = 0;
   public void printNumber() {
       System.out.println(this.number);
       System.out.println(getNumber());
   }
   public int getNumber() {
       return this.number();
   }
}

public class Reality extends Abstraction {
   int number = 1;
   public Reality() {
       this.printNumber();
   }
}

// some other class
new Reality();

我应该输出的是什么?我越来越0,0(这里的code是一个比较复杂一点,但仍是同样的问题)。
我怎样才能得到的输出是1,1?

What should the output be? I'm getting 0, 0 (the code here is a bit more complicated but still the same issue). How can I get the output to be 1,1?

推荐答案

数量现实类< STRONG>的的覆盖在抽象类的<​​code>数量。因此,抽象类仍然认为自己的数量 0

The number in the Reality class doesn't overwrite the number in the Abstraction class. Therefore, the Abstraction class still sees his own number value as 0.

一个解决方案是:

public class Reality extends Abstraction {
   public Reality() {
       number = 1;
       this.printNumber();
   }
}

由于您的数量抽象是受保护的,你可以在你的现实访问类。

Because your number in Abstraction is protected, you can access it in your Reality class.

另一个例子是一种方法的一个参数:

Another example is a parameter in a method:

private int number;

public void myMethod(int number){
    number = 2;
}

私人诠释号字段的不会设置,相反,的参数数量将被设置为 2

Your private int number field won't be set, instead, the parameter number will be set as 2.

最后,在这个超级关键字词,请参阅类的编辑:

Finally, a word on the this and super keywords, see an edit of your classes:

public abstract class Abstraction() {
   protected int number = 0;
   public void printNumber() {
       System.out.println(this.number);
       System.out.println(getNumber());
   }
   public int getNumber() {
       return this.number();
   }
}

public class Reality extends Abstraction {
   int number = 1;
   public Reality() {
       System.out.println(number); //Will print 1
       System.out.println(this.number); //Will print 1
       System.out.println(super.number); //Will print 0
   }
}

这篇关于Java抽象类(这个关键字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆