[英]How to access outer class variable using inner static class object
I'm studying inner classes in java. 我正在用Java学习内部类。 I have seen that if inner class is non static then it can easily access the outer class variable.
我已经看到,如果内部类是非静态的,则可以轻松访问外部类变量。 But what if inner class is static, then how can we take a access of outer class's variable using static's class object ?
但是,如果内部类是静态的,那如何使用静态的class对象访问外部类的变量呢?
Below is my code, where am accessing outer class variable from inner class 下面是我的代码,其中从内部类访问外部类变量
package org;
public class Outerclass {
String name = "Europe";
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
System.out.println(this.name);
}
static class innerclass {
void updatename() {
Outerclass o = new Outerclass();
o.setname("USA");
}
}
public static void main(String[] args) {
Outerclass b = new Outerclass();
b.name; // why this error here ? "Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
innerclass i = new innerclass();
i.updatename();
}
}
You can't access non-static contents inside the static content 您无法访问静态内容内的非静态内容
When we create static inner class by default it will created as a outer template as a association of inner template. 默认情况下,当我们创建静态内部类时,它将作为外部模板创建为内部模板的关联。 So we can load both together but only static things can be inside the static inner class.
因此,我们可以将两者加载在一起,但是只有静态的东西才能在静态内部类中。
Now there are no connection between objects of the classes. 现在,类的对象之间没有连接。 But there are connection between the templates.
但是模板之间有联系。
Following is your code I have done some modification might help you 以下是您的代码,我做了一些修改可能会帮助您
public class Demo {
String name = "Europe";
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
System.out.println(this.name);
}
static class innerclass {
void updatename() {
Demo o = new Demo();
o.setname("USA");
}
}
public static void main(String[] args) {
Demo b = new Demo();
String a = b.name; // why this error here ? "Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
System.out.println(a);
innerclass i = new innerclass();
i.updatename();
}
}
Inner static class behives same as normal class: 内部静态类行为与普通类相同:
It is used mostly in two scenarios : 它主要用于两种情况 :
Non-static inner class: 非静态内部类:
...inner classes can access all members of the declaring class, even private members.
...内部类可以访问声明类的所有成员,甚至是私有成员。 In fact, the inner class itself is said to be a member of the class;
实际上,内部类本身就是该类的成员。 therefore, following the rules of object-oriented engineering, it should have access to all members of the class.
因此,遵循面向对象工程的规则,它应该有权访问该类的所有成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.