难度级别: 简单
程序
程序一
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) 5
c) 运行时错误
d) 这些都不是
程序二
2) 以下程序的输出是什么?
public class Test implements Runnable
{
public void run()
{
System.out.printf(" 线程正在运行 ");
}
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(" juejin ");
}
}
复制代码
a) juejin 线程正在运行
b) 线程正在运行 juejin
c) 编译错误
d) 运行时间错误
程序三
3) 以下程序的输出是什么?
class Temp
{
private Temp(int data)
{
System.out.printf("构造函数调用");
}
protected static Temp create(int data)
{
Temp obj = new Temp(data);
return obj;
}
public void myMethod()
{
System.out.printf("方法调用");
}
}
public class Test
{
public static void main(String[] args)
{
Temp obj = Temp.create(20);
obj.myMethod();
}
}
复制代码
a) 构造函数调用方法调用
b) 编译错误
c) 运行时错误
d) 以上都不是
程序四
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) 运行时错误
程序五
5) 以下程序的输出是什么?
class Base
{
public static String s = "超类";
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超类
文章后半部分是程序的输出及解析

输出及解析
程序一输出
答案:
(a)
复制代码
说明:
私有构造函数]不能被用来初始化类之外的对象,它是内,因为它已不再是可见的外部类中定义。
程序二输出
答案:
(C)
复制代码
说明:
构造函数不能包含在 try/catch 块中。
程序三输出
答案:
(a)
复制代码
说明:
当构造函数被标记为私有时,从某个外部类创建该类的新对象的唯一方法是使用创建新对象的方法,如上面程序中定义的那样。方法 create() 负责从其他一些外部类创建 Temp 对象。一旦创建了对象,就可以从创建对象的类中调用它的方法。
程序四答案
回答 :
(a)
复制代码
说明:
构造函数可以链接和重载。当调用 Test() 时,它会创建另一个调用构造函数 Test(int temp) 的 Test 对象。
程序五答案
回答 :
(c)
复制代码
说明:
对超类的构造函数调用必须是派生类的构造函数中的第一条语句。
以上就是本篇文章的所有内容了
















