Java继承:在超类中调用子类方法
我对Java很陌生,想知道是否可以在超类中调用子类方法.如果要进行继承,在哪里设置 public static void main .
I'm very new to java and would like to know whether calling a subclass method in a superclass is possible. And if doing inheritance, where is the proper place to set public static void main.
超类
public class User {
private String name;
private int age;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
子类
public class Admin extends User {
private int permissionLevel;
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
}
我对Java很陌生,想知道是否调用子类 超类中的方法是可能的.
I'm very new to java and would like to know whether calling a subclass method in a superclass is possible.
超类对其子类一无所知,因此,您不能在超类中调用子类 instance 方法.
A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.
在哪里设置公共static void main的适当位置.
where is the proper place to set public static void main.
由于许多因素,我不建议将main
方法放在Admin
类或User
类中.而是创建一个单独的类来封装main
方法.
I wouldn't recommend putting the main
method in the Admin
class nor the User
class for many factors. Rather create a separate class to encapsulate the main
method.
示例:
public class Main{
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}