代码如下所示,TestEX是非静态类,而它的主方法是静态的,TestEX类中含有两个内部类,两个内部类也是非静态的,内部类中的方法同样也是非静态的。
问题是:在静态的主方法中,实例化了内部类,为什么就可以调用非静态了呢?
]有点绕不过来了。
- public class TestEX{
- public class IntegerException extends Exception {
- String message;
- public IntegerException(int m) {
- message = "age " + m +" is wrong!";
- }
- public String toString() {
- return message;
- }
- }
- public class People {
- private int age;
- void setAge(int age) throws IntegerException {
- if (age >= 160 || age <= 0) {
- throw new IntegerException(age);
- }
- else {
- this.age = age;
- }
- }
- int getAge() {
- System.out.println("age " + age + " is right!");
- return age;
- }
- }
- public static void main(String[] args) {
- TestEX.People wang = new TestEX().new People();
- TestEX.People zhang = new TestEX().new People();
- try{
- wang.setAge(180);
- System.out.println(wang.getAge());
- }catch(IntegerException e){
- System.out.println(e.toString());
- }
- try{
- zhang.setAge(37);
- System.out.println(zhang.getAge());
- }catch (IntegerException e) {
- System.out.println(e.toString());
- }
- }
- }
复制代码
|
|