[英]Why can't we use this instance in the static method of extended class?
Base class 基类
class Basics415 {
Basics1 b1 = new Basics1();
public static void main_hooo(){
out.println("1234");
}
void main_ho(){
}
}
Extended class 扩展类
public class Basics5 extends Basics415{
public static void main(String[] args){
this.main_hooo(); // this line throws error.
}
}
Why we aren't able to use this instance inside a static method of the extended class? 为什么我们不能在扩展类的静态方法中使用此实例?
Your main
method is static, which means there is no instance of Basic associated with it so this
won't work. 您的main
方法是静态的,这意味着没有与之关联的Basic实例,因此this
不起作用。 To access the static methods of Basics415
, you should refer to them explicitly like this: 要访问Basics415
的静态方法,您应该像这样明确地引用它们:
public class Basics5 extends Basics415{
public static void main(){
Basics415.main_hooo();
}
}
You could also just do this since Basic5
extends Basic415
. 由于Basic5
扩展了Basic415
您也可以这样做。 Both are acceptable, but your org may have their own style guidelines: 两者都可以接受,但是您的组织可能有自己的样式准则:
public class Basics5 extends Basics415{
public static void main(){
main_hooo();
}
}
That is not the correct way to access a static method. 那不是访问静态方法的正确方法。 this
is not static. this
不是静态的。 Instead do Basic5.main_hooo()
取而代之的是Basic5.main_hooo()
this和static彼此相反,就这么简单。如果要使用它,请在非静态方法中使用它。
The main() method must be defined with a String[] parameter if you want it to execute first. 如果要首先执行main()方法,则必须使用String []参数定义它。 Also, main() is a static method (it belongs to the class). 而且,main()是静态方法(它属于该类)。 There is no instance (this) to refer to. 没有要引用的实例。
Use the class name to call it within main: 使用类名称在main中调用它:
Basics415.main_hooo(); // this line no longer throws an error.
For static method not require create an object, 对于不需要创建对象的静态方法,
public static void main(String[] args) {
Basics415 b = new Basics415();
b.main_hooo();// output : 1234
main_hooo();// output : 1234
Basics415.main_hooo();// output : 1234
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.