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

博客围绕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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MrYuShiwen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值