假设我有一个类“Person”和另一个类“Survey”,它扩展了 person,因此 Survey 是子类,Person 类是父类。 Person 是我编写的第一个类,因此现在在那里定义了 main 方法,因为我有一个子类,我可以从父类中的 main 方法调用子类的方法吗(或者我是否需要继续将 main 方法转移到尽管我确信这永远不会是必要的......)?如果是这样,这是否与子类继承父类的属性但父类不继承子类的任何属性的概念相悖?请务必回复。提前致谢。
此外,我还阅读了另一篇文章,其中有一个单独的类,可能是“driver.java”只是用于主方法,所以这是否意味着所有类都必须导入到此类中,以便我们从主类中的其他类调用方法方法?
我希望我的问题不会太复杂。
最佳答案
我来给你解释一下
当您通过调用
new
创建子类的实例时关于sub class type
,然后immediately
它的Super class constructor is called
,并且它保持going till
Object class
,这称为Constructor chaining
.所有
instance variable
是declared and initialized
在此过程中。和
most important
是,当它调用子类的构造函数时,它会转到其父类(super class),依此类推,直到 Object 类,然后1st creating the Object class object
,then the class under
它,till it reaches the subclass on whose class new was called
,你会看到constructor of the super class is called first then its subclass's
对于您的上述问题,我还创建了一个与我给出的理论解释相吻合的示例。
例如:
public class a {
public static void main(String[] args) {
B b = new B();
b.go();
}
}
class B extends a{
public void go(){
System.out.println("hello");
}
}
关于java - main方法可以放在父类中吗?如果是这样,可以在该 main 方法中实例化子对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10917171/