内部类的用法

相当于实例变量的内部类

package Test.Test04;
public class Test04 {
    public static void main(String args[]){
      Human.Dog a = new Human().new Dog("yang",10);
       a.print();
       System.out.println(a);
       Human b = a.human();
       b.print();
       System.out.println(b);
    }

}
class Human {
    public String name="huang";
    public int age=100;
    public void print(){
        System.out.println("Human "+name+" "+age);
    }
    public class Dog {
      public String name;
      public int age;

        Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public void print() {
            String humanName = Human.this.name;
            int humanAge = Human.this.age;
            Human.this.print();
            System.out.println("Dog "+this.name + " " +this.age+" Human "+humanName+" "+humanAge);
        }
       public Human human(){
            return Human.this;
       }
    }
}

在这里插入图片描述
此种内部类想要实例化必须先实例外部类,既 Human.Dog a = new Human().new Dog(“yang”,10);另外需要注意的是:在实例化的内部类方法体中有指向外部类的指针既:Human.this,我们可以用这个指针访问外部类属性和方法,既: Human.this.print(); Human.this.print(); Human.this.name;

相当于静态变量的内部类

package Test.Test03;
public class Test03 {
    public static void main(String args[]){
        Human.Dog dog1 = new Human.Dog("大黄",10);
        System.out.println(dog1);
        dog1.print();
        Human.Dog dog2 = new Human.Dog("大黑",11);
        dog2.print();
        Human human = new Human("yang",20);
        human.feed(dog1);
        human.feed(dog2);

   }
}
class Human {
    public static String country="china";
    public static int birth=5000;
    public int age;
    public String name;
    Human(String name,int age){
     this.name = name;
     this.age = age;
    }
    public void feed(Dog dog){
        System.out.println("一个"+age+"岁的叫"+name+"的人正在喂"+dog.name);
    }
    public static void print(){
        System.out.println("Human "+country+" "+birth);
    }
    public static class Dog {
       public String name;
       public int age;
        Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }
      public void print(){
             String humanName = Human.country;
             int humanAge = Human.birth;
            Human.print();
            System.out.println("dog "+this.name+" "+this.age+" Human "+humanName+" "+humanAge);
      }
    }
}

在这里插入图片描述

这种内部类是被static修饰的,所以是静态的,静态内部类是也可以被实例化,但不需要实例化外部类: Human.Dog dog1 = new Human.Dog(“大黄”,10);需要注意的是:静态内部类中可以直接访问外部类的静态变量和静态方法,不能直接访问成员变量与成员方法,因为它的外部类没实例化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值