A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 路文龙 中级黑马   /  2015-3-8 16:09  /  446 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

代码如下所示,TestEX是非静态类,而它的主方法是静态的,TestEX类中含有两个内部类,两个内部类也是非静态的,内部类中的方法同样也是非静态的。
问题是:在静态的主方法中,实例化了内部类,为什么就可以调用非静态了呢?
]有点绕不过来了。
  1. public class TestEX{

  2.     public class IntegerException extends Exception {
  3.         String message;
  4.         public IntegerException(int m) {
  5.             message = "age " + m +" is wrong!";
  6.         }
  7.         public String toString() {
  8.             return message;
  9.         }
  10.     }

  11.     public  class People {
  12.         private int age;
  13.         void setAge(int age) throws IntegerException {
  14.             if (age >= 160 || age <= 0) {
  15.             throw new IntegerException(age);
  16.             }
  17.             else {
  18.                 this.age = age;
  19.             }
  20.         }
  21.         int getAge() {
  22.             System.out.println("age " + age + " is right!");
  23.             return age;
  24.         }
  25.     }

  26.     public static void main(String[] args) {
  27.         TestEX.People wang = new TestEX().new People();
  28.         TestEX.People zhang = new TestEX().new People();
  29.         try{
  30.             wang.setAge(180);
  31.             System.out.println(wang.getAge());
  32.         }catch(IntegerException e){
  33.             System.out.println(e.toString());
  34.         }
  35.         try{
  36.             zhang.setAge(37);
  37.             System.out.println(zhang.getAge());
  38.         }catch (IntegerException e) {
  39.             System.out.println(e.toString());
  40.         }
  41.     }
  42. }
复制代码




0 个回复

您需要登录后才可以回帖 登录 | 加入黑马