毕向东——JAVA基础——面向对象练习四错题

这些题是我第一次没做对,记录下来,便于之后复习。

1、静态方法中可以创建对象

interface A{}
class B implements A
{
	public String test()
	{
		return "yes";
	}
}
class Demo
{
	static A get()
	{
		return new B();
	}
	public static void main(String[] args)
	{
		A a=get();
		System.out.println(a.test());
	}
}

编译失败,因为A接口中没有定义test方法。

2、子类中没有创建新的属性i,所以子类中的i的改变也会造成父类中i值改变。

class Super
{
	int i=0;
	public Super(String a)
	{
		System.out.println("A");
		i=1;	
	}
	public Super()
	{
		System.out.println("B");
		i+=2;
	}
}
class Demo extends Super
{
	public Demo(String a)
	{
		//super();
		System.out.println("C");
		i=5;				
	}
	public static void main(String[] args)
	{
		int i=4;
		Super d=new Demo("A");
		System.out.println(d.i);
	}
}

//B C 5 一行一个

3、两道题进行比较

class Demo
{
	public static void main(String[] args)
	{
		try
		{
			showExce(); 
			System.out.println("A");
		}
		catch(Exception e)
		{
			System.out.println("B");
		}
		finally
		{
			System.out.println("C");
		}
		System.out.println("D");
	}
	public static void showExce()throws Exception
	{
		throw new Exception();
	}
}

//B C D 一行一个

class Demo
{	
	public static void func() throw Exception
	{
		try
		{
			throw new Exception();
			System.out.println("A");
		}
		catch(Exception e)
		{
			System.out.println("B");
		}
	}
	public static void main(String[] args)
	{
		try
		{
			func();
		}
		catch(Exception e)
		{
			System.out.println("C");
		}
		System.out.println("D");
	}
}

//编译失败。 因为打印“A”的输出语句执行不到。

记住:throw单独存在,下面不要定义语句,因为执行不到。与return类似

4、

class Demo
{	
	public void func()
	{
		//位置1;
		new  Inner();
		
	}
	class Inner{}
	public static void main(String[] args)
	{
		Demo d=new Demo();
		// 位置2 
		new Inner();
	}
}
A.在位置1写 new Inner();//ok
B.在位置2写 new Inner();//不可以,因为主函数是静态的。如果访问inner需要被static修饰。
C.在位置2写 new d.Inner();//错误,格式错误。 new new Demo().Inner();

D.在位置2写 new Demo.Inner();//错误,因为inner不是静态的。

扫描二维码关注公众号,回复: 1562912 查看本文章

5、注意+和static用法

class Test
{ 
	public static String output=""; 
	public static void foo(int i)
	{ 
		try
		{ 
			if(i==1)
				throw new Exception(); 	
			output+="1"; 
		} 
		catch(Exception e)
		{ 
			output+="2"; 
			return; 
		} 
		finally
		{ 
			output+="3"; 
		} 
		output+="4"; 
	}
	public static void main(String args[])
	{ 
		foo(0);
		System.out.println(output);//134
		foo(1); 
		System.out.println(output); //13423
	}
} 

猜你喜欢

转载自blog.csdn.net/yaocong1993/article/details/80051976