不调用parentsclass构造函数,可以在java中直接调用childclass构造函数
Without calling parents class constructor,it is possible to call direct child class constructor in java
我有一个 parents class 其名称 'parents' 和 child class 其名称 'child' 扩展 parent class。如果 child class 和 parents class 都有相同的参数但不同的行为构造函数那么如果我创建 child class objcet 它会自动调用 parents class 构造函数,我不 want.how 这是可能的。
例如
class parents
{
parents()
{
System.out.println("hello, i am
parents class constructor");
}
}
class child extends parents
{
child()
{
System.out.println("hello, i am
child class constructor");
}
}
class main
{
public static void
main(String[] args)
{
child c = new child();
}
}
现在这里,
输出是......
hello, i am parents class constructor
hello, i am child class constructor
但我只想要...
hello, i am child class constructor
仅表示 child class 构造函数是 运行 而不是 parent class.
怎么可能...
每当调用 class 的构造函数时,也会隐式调用其父 class 的构造函数。
正如@SilvioMayolo 在评论中指出的那样,推理是
"If you don't want the child to behave like the parent class, then it shouldn't be a parent class."
从概念上讲,它是一个子项 class 是因为子项从其父项 继承了一些属性或功能。如在您的示例中,如果您不希望在调用子构造函数时打印 "hello, i am parent class constructor"
,则实际上不需要子项的父项 class 实际上是其父项。
因此,您想要实现的功能在 Java 中是不可能的,因为它是该语言的隐含功能。
我有一个 parents class 其名称 'parents' 和 child class 其名称 'child' 扩展 parent class。如果 child class 和 parents class 都有相同的参数但不同的行为构造函数那么如果我创建 child class objcet 它会自动调用 parents class 构造函数,我不 want.how 这是可能的。
例如
class parents
{
parents()
{
System.out.println("hello, i am
parents class constructor");
}
}
class child extends parents
{
child()
{
System.out.println("hello, i am
child class constructor");
}
}
class main
{
public static void
main(String[] args)
{
child c = new child();
}
}
现在这里,
输出是......
hello, i am parents class constructor
hello, i am child class constructor
但我只想要...
hello, i am child class constructor
仅表示 child class 构造函数是 运行 而不是 parent class.
怎么可能...
每当调用 class 的构造函数时,也会隐式调用其父 class 的构造函数。
正如@SilvioMayolo 在评论中指出的那样,推理是
"If you don't want the child to behave like the parent class, then it shouldn't be a parent class."
从概念上讲,它是一个子项 class 是因为子项从其父项 继承了一些属性或功能。如在您的示例中,如果您不希望在调用子构造函数时打印 "hello, i am parent class constructor"
,则实际上不需要子项的父项 class 实际上是其父项。
因此,您想要实现的功能在 Java 中是不可能的,因为它是该语言的隐含功能。