难度级别: 简单

程序

程序一

1) 以下程序的输出是什么?

public class RuntimePolymorphism
{
	public static void main(String[] args)
	{
		A a = new B();
		B b = new B();
		
		System.out.println(a.c + " " + a.getValue()
			+ " " + b.getValue() + " " + b.getSuperValue());
	}
}

class A
{
	protected char c = 'A';
	char getValue()
	{
		return c;
	}
}

class B extends A
{
	protected char c = 'B';
	char getValue()
	{
		return c;
	}
	char getSuperValue()
	{
		return super.c;
	}
}
复制代码

 


程序二

2) 以下程序的输出是什么?

public class RuntimePolymorphism
{
	public static void main(String[] args)
	{
		A a = new B();
		B b = new B();
		System.out.println(a.c + " " + a.getValue() +
			" " + b.getValue() + " " + b.getSuperValue());
	}
}

class A
{
	protected char c = 'A';
	char getValue()
	{
		return c;
	}
}
class B extends A
{
	protected char c = 'B';
	char getSuperValue()
	{
		return super.c;
	}
}
复制代码

 


程序三

3) 以下程序的输出是什么?

class test
{
	public static int y = 0;
}

class HasStatic
{
	private static int x = 100;
	
	public static void main(String[] args)
	{
		HasStatic hs1 = new HasStatic();
		hs1.x++;
		
		HasStatic hs2 = new HasStatic();
		hs2.x++;
		
		hs1 = new HasStatic();
		hs1.x++;
		
		HasStatic.x++;
		System.out.println("Adding to 100, x = " + x);
		
		test t1 = new test();
		t1.y++;
		
		test t2 = new test();
		t2.y++;
		
		t1 = new test();
		t1.y++;
		
		System.out.print("Adding to 0, ");
		System.out.println("y = " + t1.y + " " + t2.y + " " + test.y);
	}
}
复制代码

 


程序四

4) 以下程序的输出是什么?

public class Except
{
	public static void main(String[] args)
	{	
		try
		{
			throw new Error();
		}
		catch (Error e)
		{
			try
			{
				throw new RuntimeException();
			}
			catch (Throwable t)
			{

			}
		}
			System.out.println("haiyong");
	}
}
复制代码

a) 由于第 23 行导致的编译错误
b) 由于第 24 行导致的编译错误
c) 由于第 25 行导致的编译错误
d) 以上所有

 


程序五

5) 以下程序的输出是什么?

public class Boot
{
	static String s;
	static
	{
		s = "";
	}
	{
		System.out.println("haiyong ");
	}
	static
	{
		System.out.println(s.concat("practice.haiyong "));
	}
	Boot()
	{
		System.out.println(s.concat("Quiz.haiyong"));
	}
	public static void main(String[] args)
	{
		new Boot();
		System.out.println("Videos.haiyong");
	}
}
复制代码

 


文章后半部分是程序的输出及解析

【Java练习题】Java 程序的输出 | 第十九套(含解析)_java


输出及解析

程序一输出

输出

ABBA
复制代码

说明

这里没有多态的影响;A 中的实例变量 c 只是隐藏在 B 中——ac\

是“A”,因为它在类 A 中是这样设置的——a.getValue() 返回“B”,因为对象是 B 类型


程序二输出

输出

AAAA
复制代码

说明

此处不能使用方法的多态性概念,因为在 B 类中没有函数重载 A 类中的方法。


程序三输出

输出

Adding to 100, x = 104
Adding to 0, y = 3 3 3
复制代码

说明

本例显示了静态的属性。当变量被声明为静态时,将创建一个变量副本并在类级别的所有对象之间共享。静态变量本质上是全局变量。类的所有实例共享相同的静态变量。


程序四答案

输出

haiyong
复制代码

说明

抛出和处理错误和运行时异常是合法的。RuntimeException 是 Throwable 的子类。


程序五答案

输出 :

practice.haiyong 
haiyong 
Quiz.haiyong
Videos.haiyong
复制代码

说明:

静态 init 块在实例 init 块之前运行(分别按照它们出现的顺序)。初始化构造函数和初始化块的顺序无关紧要,初始化块总是在构造函数之前执行。


以上就是本篇文章的所有内容了