是否可以从另一个(在同一类中,而不是从子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法)?
当前回答
是的,可以使用this()从另一个构造函数调用一个构造函数
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
其他回答
是的,可以使用this()从另一个构造函数调用一个构造函数
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
我会告诉你一个简单的方法
构造函数有两种类型:
默认构造函数参数化构造函数
我将在一个示例中解释
class ConstructorDemo
{
ConstructorDemo()//Default Constructor
{
System.out.println("D.constructor ");
}
ConstructorDemo(int k)//Parameterized constructor
{
this();//-------------(1)
System.out.println("P.Constructor ="+k);
}
public static void main(String[] args)
{
//this(); error because "must be first statement in constructor
new ConstructorDemo();//-------(2)
ConstructorDemo g=new ConstructorDemo(3);---(3)
}
}
在上面的示例中,我展示了3种类型的调用
this()调用必须是构造函数中的第一条语句这是无名称对象。这将自动调用默认构造函数。3.这将调用参数化构造函数。
注:这必须是构造函数中的第一条语句。
使用此关键字,我们可以在同一类中的另一个构造函数中调用一个构造函数。
示例:-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
可以通过this(…)关键字(当需要从同一类调用构造函数时)或super(…)关键词调用另一个构造函数(当您需要从超类调用构造函数时)。
但是,这样的调用必须是构造函数的第一条语句。要克服这个限制,请使用这个答案。
是的,您可以从另一个构造函数调用构造函数。例如:
public class Animal {
private int animalType;
public Animal() {
this(1); //here this(1) internally make call to Animal(1);
}
public Animal(int animalType) {
this.animalType = animalType;
}
}
您还可以从Java中的构造函数链接