Java抽象类(这个关键字) [英] Java Abstract Class (this keyword)
问题描述
我想我误解的东西,如果是这样,我需要帮助。
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屋!