当前位置 : 主页 > 编程语言 > java >

Java向上转型向下转型

来源:互联网 收集:自由互联 发布时间:2022-07-07
public class Teacher extends Person { public Teacher () { } public void say (){ System . out . println ( "teacher" ); } public Teacher ( String name ) { super ( name ); } } public class Person { private String name ; public Person () { } pu
public class Teacher extends Person{

public Teacher() {
}

public void say(){
System.out.println("teacher");
}

public Teacher(String name) {
super(name);
}
}public class Person {
private String name;

public Person() {
}

public void say(){
System.out.println("person");
}

public Person(String name) {
this.name = name;
}
}public class Main {

public static void main(String[] args) {
//向上转型
Person person = new Teacher("Tom");
System.out.println(person.toString());

// 父类向子类只能强转
// Teacher teacher = new Person("A");
Teacher teacher = (Teacher) new Person("A");

}
}

向上向下走一遭

public static void main(String[] args) {
Student student = new Student();
student.setAge(12);
student.setName("A");
Student sign = (Student)getSign(student);
System.out.println(JSON.toJSONString(sign));
}

static Person getSign(Person person){
return person;
}


上一篇:java常用判空
下一篇:没有了
网友评论