先决条件—— Java构造函数
1) 以下程序的输出是什么?
class Helper { private int data; private Helper() { data = 5 ; } } public class Test { public static void main(String[] args) { Helper help = new Helper(); System.out.println(help.data); } } |
a) 编译错误 b) 五, c) 运行时错误 d) 这些都不是
答案。 (a) 说明: A. 私有构造函数 无法用于在定义对象的类之外初始化对象,因为外部类不再可以看到该对象。
2) 以下程序的输出是什么?
public class Test implements Runnable { public void run() { System.out.printf( " Thread's running " ); } try { public Test() { Thread.sleep( 5000 ); } } catch (InterruptedException e) { e.printStackTrace(); } public static void main(String[] args) { Test obj = new Test(); Thread thread = new Thread(obj); thread.start(); System.out.printf( " GFG " ); } } |
a) GFG线程正在运行 b) 线程正在运行GFG c) 编译错误 d) 运行计时器错误
答案。 (c) 说明: 构造函数不能包含在try/catch块中。
3) 以下程序的输出是什么?
class Temp { private Temp( int data) { System.out.printf( " Constructor called " ); } protected static Temp create( int data) { Temp obj = new Temp(data); return obj; } public void myMethod() { System.out.printf( " Method called " ); } } public class Test { public static void main(String[] args) { Temp obj = Temp.create( 20 ); obj.myMethod(); } } |
a) 构造函数调用方法调用 b) 编译错误 c) 运行时错误 d) 以上都没有
答案。 (a) 说明: 当构造函数被标记为private时,从某个外部类创建该类的新对象的唯一方法是使用创建新对象的方法,如上面在程序中定义的。方法create()负责从其他外部类创建临时对象。创建对象后,可以从创建对象的类调用其方法。 4) 以下程序的输出是什么?
public class Test { public Test() { System.out.printf( "1" ); new Test( 10 ); System.out.printf( "5" ); } public Test( int temp) { System.out.printf( "2" ); new Test( 10 , 20 ); System.out.printf( "4" ); } public Test( int data, int temp) { System.out.printf( "3" ); } public static void main(String[] args) { Test obj = new Test(); } } |
a) 12345 b) 编译错误 c) 15 d) 运行时错误
答案。 (a) 说明: 构造函数可以被链接起来 而且超载。调用Test()时,它会创建另一个调用构造函数Test(int temp)的测试对象。
5) 以下程序的输出是什么?
class Base { public static String s = " Super Class " ; public Base() { System.out.printf( "1" ); } } public class Derived extends Base { public Derived() { System.out.printf( "2" ); super (); } public static void main(String[] args) { Derived obj = new Derived(); System.out.printf(s); } } |
a) 21超级班 b) 超级21级 c) 编译错误 d) 12级 答案。 (c) 说明: 对超类的构造函数调用必须是派生类的构造函数中的第一条语句。 私有的 本文由 马扬克·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。