Java中匿名子类 的 匿名对象、匿名子类 的 非匿名对象、非匿名类 的 匿名对象、非匿名类 的 非匿名对象

/**
 * @Author: YuShiwen
 * @Date: 2020/11/18 2:06 PM
 * @Version: 1.0
 */
public class AnonymousTest {
    
    

    public static void main(String[] args) {
    
    
        //非匿名类 的 非匿名对象,即类名为Freshman,对象名为:freshman
        Freshman freshman = new Freshman("Mr.Yu",18);
        freshman.setUniversity();
        System.out.println(freshman);


        //非匿名类 的 匿名对象,即new Freshman("Ms.cheng", 18),知其类名为Freshman,对象名匿名了
        freshman.printStudent((new Freshman("Ms.cheng", 18)));

        //匿名子类 的 非匿名对象,即以下语句,
        // 知其父类名为Student,不知其子类名,创建了子类对象名为:firstClassStudent 用父类接收
        Student firstClassStudent = new Student("小明",19) {
    
    

            @Override
            public void setUniversity() {
    
    
                this.school = "Tsinghua University";
            }
        };
        firstClassStudent.setUniversity();
        System.out.println(firstClassStudent);

        //匿名子类 的 匿名对象,即以下语句
        // 知其父类名为Student,不知其子类名,用子类创建对象,也不知其对象名
        freshman.printStudent(new Student("小华",18) {
    
    
            @Override
            public void setUniversity() {
    
    
                this.school = "Peking University";
            }
        });
    }

}


//抽象类
abstract class Student{
    
    
    String name;
    int age;
    String school;

    public Student() {
    
    
    }

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

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", school='" + school + '\'' +
                '}';
    }

    public abstract void setUniversity();

}



class Freshman extends Student{
    
    

    public Freshman() {
    
    
    }

    public Freshman(String name, int age) {
    
    
        super(name, age);
    }

    @Override
    public void setUniversity() {
    
    
        this.school = "Yangtze University";
    }

    public void printStudent(Student student){
    
    
        System.out.println(student);
    }

}

输出结果:

Student{name='Mr.Yu', age=18, school='Yangtze University'}
Student{name='Ms.cheng', age=18, school='null'}
Student{name='小明', age=19, school='Tsinghua University'}
Student{name='小华', age=18, school='null'}

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/MrYushiwen/article/details/109774229