JAVASE.内部类

1内部类

内部类是指在一个类中包含另一个类,其中外面的类叫做外部类,里面的叫做内部类
成员内部类及特点
成员内部类可以直接无条件访问外部类的任何成员
在外部类中不能直接调用内部类的方法成员
代码实现:

	
public class Animal {
    private String name;
    private int age;

    public Animal() {
    }

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

    class cat {
        int mousecount;
        public void mouse() {
            System.out.println("我会捉老鼠,我是一只猫");
            System.out.println(name);
            System.out.println(age);
            eat();
            
        }
    }

    public void eat() {
        System.out.println("吃");
        
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

在测试类中创建成员内部类条件

	public class Test01 {
    public static void main(String[] args) {
        //方法一:
        Animal a = new Animal();
        Animal.cat cat1 = a.new cat();
        System.out.println(cat1);
        //方法二
        Animal.cat cat = new Animal().new cat();
        System.out.println(cat);
        
    }
}


2.匿名内部类

匿名内部类是内部类的简化形式
不需要写类的名称
用途快速创建一个父类的子类或者接口的实现类对象
继承的匿名内部类代码实现:

public class TestStudent {
    public static void main(String[] args) {
        Student s = new Student();
        s.drink();
        s.eat();
        Person p = new Person() {
            @Override
            public void eat() {
                System.out.println("重写的吃");
            }

            @Override
            public void drink() {
                System.out.println("重写的喝");
            }
        };
        p.drink();
        p.eat();

    }
}


接口的匿名内部类代码实现:

package com.ithema.Text06;

public interface Fly {
    public abstract void fly();
}
package com.ithema.Text06;

public class SuperPerson implements Fly {

    @Override
    public void fly() {
        System.out.println("超人会飞");

    }
}
package com.ithema.Text06;

public class TextSuperPerson {
    public static void main(String[] args) {
        SuperPerson sp = new SuperPerson();
        sp.fly();
        //匿名内部类实现

        new Fly() {

            @Override
            public void fly() {
                System.out.println("匿名内部类的超人会飞");

            }
        }.fly();
    }
}


匿名内部类的格式总结:
父类名/接口名 对象名 = new 父类名/接口名(){
//重写的方法
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章