java 父类访问子类,Java继承:在超类中调用子类方法

这篇博客探讨了在Java中是否可以在超类中调用子类的方法,解释了由于继承的特性,超类无法直接调用子类实例方法。同时,建议将main方法放在单独的类中,以保持良好的代码组织结构。示例展示了如何创建User和Admin类,并在独立的Main类中执行main方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Superclass

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();

}

}

Subclass

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);

}

}

解决方案

I'm very new to java and would like to know whether calling a subclass

method in a superclass is possible.

A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.

where is the proper place to set public static void 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.

Example:

public class Main{

public static void main(String []args) {

User user1 = new Admin("Bill", 18, 2);

System.out.println("Hello "+user1.getName());

user1.getLevel();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值