/*** @Author: YuShiwen* @Date: 2020/11/18 2:06 PM* @Version: 1.0*/publicclassAnonymousTest { publicstaticvoidmain(String[] args) { //非匿名类 的 非匿名对象,即类名为Freshman,对象名为:freshmanFreshmanfreshman=newFreshman("Mr.Yu",18); freshman.setUniversity(); System.out.println(freshman); //非匿名类 的 匿名对象,即new Freshman("Ms.cheng", 18),知其类名为Freshman,对象名匿名了freshman.printStudent((newFreshman("Ms.cheng", 18))); //匿名子类 的 非匿名对象,即以下语句,// 知其父类名为Student,不知其子类名,创建了子类对象名为:firstClassStudent 用父类接收StudentfirstClassStudent=newStudent("小明",19) { publicvoidsetUniversity() { this.school="Tsinghua University"; } }; firstClassStudent.setUniversity(); System.out.println(firstClassStudent); //匿名子类 的 匿名对象,即以下语句// 知其父类名为Student,不知其子类名,用子类创建对象,也不知其对象名freshman.printStudent(newStudent("小华",18) { publicvoidsetUniversity() { this.school="Peking University"; } }); } } //抽象类abstractclassStudent{ Stringname; intage; Stringschool; publicStudent() { } publicStudent(Stringname, intage) { this.name=name; this.age=age; } publicStringtoString() { return"Student{"+"name='"+name+'\''+", age="+age+", school='"+school+'\''+'}'; } publicabstractvoidsetUniversity(); } classFreshmanextendsStudent{ publicFreshman() { } publicFreshman(Stringname, intage) { super(name, age); } publicvoidsetUniversity() { this.school="Yangtze University"; } publicvoidprintStudent(Studentstudent){ 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'} Processfinishedwithexitcode0