调用父构造函数Java
问题描述:
所以我试图制作一个Java GUI计算器,并开始怀疑在一个类扩展另一个类的场景中是否会有所不同,在扩展中调用super.functionname而不是只调用functionname类。调用父构造函数Java
class frame extends JFrame{
public buttonframe(){
// any difference between this.add.. or super.add..
}
}
然后,我做了几个类试验一点,我过来的东西,我不明白。
class A{
public A(){
System.out.println("A");
h();
}
public void h(){
String className = this.getClass().getName();
System.out.println(className);
}
}
class B extends A{
public B(){
System.out.println("B");
h();
}
}
运行:
public static void main(String[] args){
new A();
new B();
}
产生输出:
> A calculator.A
> A calculator.B
> B calculator.B
我知道,扩展的类会调用父类的构造函数,但为什么它产生的结果计算器.B(尽管我不知道为什么它必须这样做,但我认为A classname = new B();
与它有关),而不是calculator.A当它是构造函数calle d从A类?
编辑:
class A{
public A(){
//Can I instantiate a new B() and somehow ouput "A"?
//I can do it using A.hs(); but can I do it:
//Using the method h() but with a specific keyword infront of h() so
//that it always refers to the method h() of the class A.
h();
}
public static void hs(){
System.out.println("A");
}
public void h(){
System.out.println("A");
}
}
class B extends A{
public B(){
h();
}
public void h(){
System.out.println("B");
}
}
答
其结果是,因为该语句的:
String className = this.getClass().getName();
时称为new B()
当前对象(this
)是B和因此的B
类名。
所以,完整的序列,你的情况应该是:
A() => prints A => call h() with current object of 'A' => prints classname of A
B() => calls super c'tor A() => prints A => call h() with object of 'B'
=> prints classname of B => prints B => call h() => prints classname of B
这有一定道理,当我思考的问题。我意识到我最近并没有“足够的扩展类”,因为每次使用this关键字时,它都只在同一个类中,所以我开始将此关键字与类关联起来而不是对象本身。 –
虽然有一点我很好奇。一个classname = new B(),其中函数h()在A构造函数中运行,并且都具有函数h(),其中类A打印A并且类B打印B.是否有关键字引用Ah()用在A的构造函数中?所以新的B()将输出A.我不能使用这个,并且我不能在A()中使用super。我意识到我可以使用静态函数,但这是我唯一能做的事情吗?我对Java很新,但在Csharp方面有一些经验。 –
很不清楚,你刚刚问了什么。如果您需要参考A或B的实例,您仍需要尝试创建一个或使用该类的静态引用。 – nullpointer