Java中匿名子类 的 匿名对象、匿名子类 的 非匿名对象、非匿名类 的 匿名对象、非匿名类 的 非匿名对象
【摘要】
/**
* @Author: YuShiwen
* @Date: 2020/11/18 2:06 PM
* @Version: 1.0
*/
public class AnonymousTest ...
/**
* @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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
输出结果:
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
文章来源: blog.csdn.net,作者:Mr.Yushiwen,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/MrYushiwen/article/details/109774229
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)