[英]Unable to access Method from Subclass
I'm just trying to use Method_In_SubClass() method from SubClass Class but I'm getting these errors.我只是想使用 SubClass Class 中的 Method_In_SubClass() 方法,但我遇到了这些错误。 I tried by changing Method_In_SubClass to Static but still getting errors
我尝试将 Method_In_SubClass 更改为 Static 但仍然出现错误
public class Sub {
//Method 1 : Non-Static
public void nonstatictest(){
System.out.println("This is non-Static method.");
}
//Mehod 2 : Static
public static void statictest(){
System.out.println("This is static method.");
}
//SubClass
public class SubClass{
//Method in SubClass
public void Method_In_SubClass(){
System.out.println("This is Method in SubClass");
}
}
public static void main(String args[]){
Sub SubObject = new Sub();
SubClass SubClassobject = new SubClass();
SubObject.nonstatictest();
statictest();
SubClassobject.Method_In_SubClass();
}
}
Error:错误:
Sub.java:25: error: non-static variable this cannot be referenced from a static context
SubClass SubClassobject = new SubClass();
^
1 error
Then I changed Method_In_SubClass to static but getting this error然后我将 Method_In_SubClass 更改为 static 但收到此错误
Error :Illegal static declaration in inner class Sub.SubClass
public static void Method_In_SubClass(){
^
modifier 'static' is only allowed in constant variable declarations
Sub.java:25: error: non-static variable this cannot be referenced from a static context
SubClass SubClassobject = new SubClass();
Both Main and SubClass are members of class Sub and you cannot reference a non-static member of class sub that is SubClass in Main which is a static member. Main 和 SubClass 都是 class Sub 的成员,您不能引用 class sub 的非静态成员,它是 Main 中的 SubClass,它是 static 成员。 You need make the entire SubClass into static instead of just the Method_In_SubClass().
您需要将整个子类变成 static 而不仅仅是 Method_In_SubClass()。
The Easiest way to make it work is by making SubClass as Static使其工作的最简单方法是将 SubClass 设置为 Static
public static class SubClass{
//Method in SubClass
public void Method_In_SubClass(){
System.out.println("This is Method in SubClass");
}
}
I assumed that initiating SubClass Object/Instance of the class would be same as Parent class but it's not我假设启动 class 的子类对象/实例将与父 class 相同,但事实并非如此
SubClass SubClassobject = new SubClass();
子类子类对象 = 新子类();
The correct way of initiating an object of the subclass is:启动子类的 object 的正确方法是:
Sub.SubClass SubClassobject = SubObject.new SubClass();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.