写一个Outer类,定义一个静态属性和一个非静态属性;定义一个静态内部类Inner,在其中分别定义一个普通方法show()和一个静态方法play(),并尝试在此两个方法中同时访问外部类的静态与非静态属性。
时间: 2024-09-18 15:12:33 浏览: 55
在Java中,你可以创建一个`Outer`类,然后定义一个静态属性和一个非静态属性。接着,你可以定义一个静态内部类`Inner`,并在这个内部类中定义两个方法:一个普通方法(实例方法)`show()`和一个静态方法`play()`。这里是如何实现的:
```java
public class Outer {
// 静态属性
public static String staticProperty = "This is a static property";
// 非静态属性
private String nonStaticProperty = "This is a non-static property";
// Inner静态内部类
public static class Inner {
// 普通方法 show()
public void show() {
System.out.println("Inside Inner, accessing outer's static property: " + Outer.staticProperty);
System.out.println("Inside Inner, accessing outer's non-static property: " + Outer.nonStaticProperty);
}
// 静态方法 play()
public static void play() {
Outer outerInstance = new Outer(); // 创建外层类的实例以访问非静态属性
System.out.println("Inside Inner static method, accessing outer's static property: " + Outer.staticProperty);
System.out.println("Inside Inner static method, accessing outer's non-static property: " + outerInstance.nonStaticProperty);
}
}
public static void main(String[] args) {
// 访问静态属性
System.out.println("From main, accessing outer's static property: " + Outer.staticProperty);
// 创建Inner的实例并调用show方法
Outer.Inner inner = new Outer.Inner();
inner.show();
// 直接调用静态方法play
Outer.Inner.play();
}
}
```
在这个例子中,`Inner`类中的`show()`方法可以直接访问`Outer`类的静态属性,因为它们在同一作用域内。而`play()`方法是静态的,所以在调用时需要先创建`Outer`的一个实例才能访问其非静态属性。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)