java多态存在的三个必要条件:
1.需要有继承关系的存在
2.需要有方法的重写
3.需要有父类的引用指向子类对象
希望对你有帮助。
第一题应该选D,第二题选C,D。
第一题属于多态,methodB()方法属于子类,父类没有重写子类的方法
第二题属于继承,子类可以继承父类的方法
System.out.println("1--" + a1.show(b))a1是A类引用指向A类对象,不存在多态,一定调用A类方法。A类方法有两个show(D)和show(A),b是B类引用无法转换为D类引用,但可以转换为A类引用,因此调用show(A),输出A and A。
System.out.println("2--" + a1.show(c))
输出A and A,原因同上。
System.out.println("3--" + a1.show(d))
调用show(D),输出A and D。
System.out.println("4--" + a2.show(b))
a2是A类引用指向B类对象,可能存在多态。b是B类引用无法转换为D类引用,但可以转换为A类引用,因此调用show(A),而B类重写了show(A),因此调用的是重写后的show(A),输出B and A。
System.out.println("5--" + a2.show(c))
同上,C类引用无法转换为D类引用,但可以转换为A类引用,因此调用show(A),输出B and A。
System.out.println("6--" + a2.show(d))
调用show(D),show(D)又调用父类即A类的show(D),输出A and D
System.out.println("7--" + b.show(b))
b是B类引用指向B类对象,不存在多态,一定调用B类方法。B类一共有三个方法:重写自A类的show(A)和show(D),以及新定义的show(B)。show(b)调用show(B)方法,输出B and B
System.out.println("8--" + b.show(c))
C类继承自B类,也调用show(B)方法,输出B and B
System.out.println("9--" + b.show(d))
调用show(D),show(D)又调用父类即A类的show(D),输出A and D
public class People {private String name
private Integer age
private String phone
public String getMessage() {
return "People: 姓名:"+name+",年龄:"+age+",电话:"+phone
}
public String getName() {
return name
}
public void setName(String name) {
this.name = name
}
public Integer getAge() {
return age
}
public void setAge(Integer age) {
this.age = age
}
public String getPhone() {
return phone
}
public void setPhone(String phone) {
this.phone = phone
}
} public class Student extends People{
private Integer id
public String getMessage(Integer id) {
return "Student: 姓名:"+super.getName()+",年龄:"+super.getAge()+",电话:"+super.getPhone()+",学号:"+id
}
public Integer getId() {
return id
}
public void setId(Integer id) {
this.id = id
}
} public class S {
public static void main(String[] args) {
Student student = new Student()
student.setId(13)
student.setName("李三")
student.setAge(18)
student.setPhone("123-4567-8901")
System.out.println(student.getMessage(student.getId()))
}
}