【发布时间】:2020-05-29 03:08:42
【问题描述】:
继承.java 文件
package oops.Inheritance;
public class Inheritance {
public static void main(String[] args) {
Teacher t=new Teacher("gopi");
t.name="ravi";
t.eat();
t.walk();
t.teach();
Singer s=new Singer("rock");
s.name="arjun";
s.eat();
s.walk();
person p =new person("jack");
//person p=t;//upcasting
//Teacher t=(Teacher)p;//downcasting
// boolean yo = t instanceof Teacher;//to fine whether t is is instance of teacher
// System.out.println(t instanceof Teacher);//true
// System.out.println(s instanceof Singer);//true
// System.out.println(t instanceof person);//true
// System.out.println(p instanceof Teacher);//flase
}
}
错误是
D:\study files\java files\oops\Inheritance>javac Inheritance.java
Inheritance.java:5: 错误:找不到符号
Teacher t=new Teacher("gopi");
^
符号:班主任
位置:类继承
Inheritance.java:5: 错误:找不到符号
Teacher t=new Teacher("gopi");
^
符号:班主任
位置:类继承
Inheritance.java:10: 错误:找不到符号
Singer s=new Singer("rock");
^
符号:歌手类
位置:类继承
Inheritance.java:10: 错误:找不到符号
Singer s=new Singer("rock");
^
符号:歌手类
位置:类继承
Inheritance.java:15: 错误:找不到符号
person p =new person("jack");
^
符号:类人
位置:类继承
Inheritance.java:15: 错误:找不到符号
person p =new person("jack");
^
符号:类人
位置:类继承
6 个错误
person.java
package oops.Inheritance;
public class person {
protected String name;
public person(String name){
this.name=name;
System.out.println("Inside person constructor");
}
public void walk(){
System.out.println("person"+name+"person is walking");
}
public void eat(){
System.out.println("person"+name+"person is eating");
}
public static void laughing(){
System.out.println("person is laughing");
}
}
Teacher.java
package oops.Inheritance;
public class Teacher extends person{//inheriting from person
public Teacher(String name){
super(name);//calls the constructor in the parent class
System.out.println("Inside teacher constructor");
}
public void teach(){
System.out.println(name+"Teacher is teaching");
}
public void eat(){
super.eat();//to access the parent class i.e, here person class
System.out.println("teacher"+name+"is eating");
}
}
}
singer.java
package oops.Inheritance;
public class Singer extends person{//inheriting from person
public Singer(String name){
super(name);//calls the the constructor in parent class
System.out.println("Inside singer constructor");
}
public void sing(){
System.out.println("Singer is singing");
}
public void eat(){
System.out.println("teacher"+name+"is eating");
}
}
我在最新版本的 vscode 中运行这个程序。 每次它都可以工作,但是当我从另一个包中导入类时,我会收到上述错误。
【问题讨论】:
-
所有这些类都在同一个包中吗?如果没有,您是否导入了它们?
-
您在错误的目录中。您应该位于包层次结构的根部。
cd ..并使用javac Inheritance/Inheritance.java。 -
javac时应该在java files目录下。 -
@OP 你的评论毫无意义。在执行之前,您无法得到“找不到主类”错误,并且在编译之前无法执行,并且目前无法编译。您仍然在错误的目录中。您应该在
java files目录中,即cd ..\..并发出javac oop/Inheritance/Inheritance.java。然后java oop.Inheritance.Inheritance. -
所有这些源文件都在
D:\study files\java files\oops\Inheritance中吗?如果不是,为什么不呢?在您的问题中,“每次都有效”到底是什么意思?
标签: java oop inheritance