[英]Java - Abstract classes and concrete classes
我正在完成我的任务,但是我对抽象类和具体类感到困惑,我从程序中得到错误...
假设有一个抽象类Person和一个具体的子类Student:
abstract class Person{
private String name;
public Person(String s){
name = s;
}
public String getName() {
return name;
}
public abstract void doAction(Person other);
}
class Student extends Person{
public Student(String name){
super(name);
}
public void doAction(Person other){
System.out.println("This person's name is " + getName());
}
}
然后我实现了一个main函数来测试它,但是我收到了一个错误...:
public class TestMain {
public static void main(String[] args) {
Person person;
Student student;
person = new Student("Sam");
student = person;
student.doAction(person);
}
}
据说student = person
收到错误的人说"Error: Incompatible types: Person cannot be converted to Student"
。 实际上有什么问题,为什么......? 有谁能解释这个......?
Student
是一个Person
,但不是每个Person
都是Student
。
如果您有一个Person
类型的变量,则不能将其值分配给Student
类型的变量,因为通常这可能不安全。
如果您确定它绝对是Student
(例如,您使用了检查instanceof
,或者您已经对代码进行了推理并因此“知道”),您可以转换变量; 但是面向对象编程的核心思想之一就是你不需要关心特定的子类。
这有两种方式:
首先将new Student()
分配给Student
变量,然后将该值赋给Person
变量:
student = new Student("Sam"); person = student; student.doAction(person);
这很好,因为每个Student
都是Person
,因此可以为Person
变量分配Student
变量的值。
完全放弃student
变量,因为您只需要对可以调用doAction
的Person
的引用,而不是特别是Student
:
person = new Student("Sam"); person.doAction(person);
在运行时, person
变量可以引用Person
实例,这些实例不是Student
实例。 因此,作业student = person;
不被允许。
你必须检查的运行时类型person
,为了执行强制类型转换的分配工作(当然,类型检查是不是强制性的,但建议,为了避免潜在的ClassCastException
):
if (person instanceof Student)
student = (Student) person;
package taskassignment;
public abstract class Person
{
public String name;
public Person(String n)
{
name = n;
}
public String getName()
{
return name;
}
public abstract String doAction(Person other);
}
public class Student extends Person
{
public Student(String n)
{
super(n);
}
@Override
public String doAction(Person other)
{
return "The Person Name is : "+ getName();
}
}
public static void main(String args[])
{
Person person = new Student("Sam");
Student student = (Student) person;
System.out.println(student.doAction(person));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.