匿名类,try-catch语句

初学者。

匿名类是一个子类,没有类名,用匿名类创建对象时,要直接使用父类的构造方法。

class Cry
{
	public void cry()
	{
		System.out.println("大家好");
	}
}
public class seven 
{
	public static void main(String args[])
	{
		Cry hello = new Cry()  
		{
			public void cry()
			{
				System.out.println("大家好,我是赵某某");
			}
		};
		hello.cry();
		
	}

}

输出:

大家好,我是赵某某
匿名类同样可以实现接口

interface abc
{
	int n = 100;  // 相当于final int n = 100; 若换为int n; 就不对了,接口中只有常量
	int f(int x, int y);
}
public class eight 
{
	public static void main(String args[])
	{
		abc md = new abc()
		{
			public int f(int x, int y)  //必须加public,重写不可降低权限,重写参数类型,个数以及方法名一定要与接口中方法一致
			{
				return x * y;
			}
		};
		System.out.println(md.f(5, 5));
	}
}

输出:

25

try-catch语句:

Java使用try-catch语句处理异常,将可能出现异常的操作放在try-catch语句的try中,当try中某个方法调用异常,try部分直接结束执行,转向catch部分。因此,可以把异常处理部分操作放在catch部分。

public class six    //教材上例子
{
	public static void main(String args[])
	{
		int n = 0, m = 0, t = 666;
		try
		{
			m = Integer.parseInt("8888");
			n = Integer.parseInt("ab85");  //发生异常,转向catch,t没有机会赋值了
			t = 999;
		}
		catch(NumberFormatException e)
		{
			System.out.println("发生异常:" + e.getMessage());
			n = 123;
		}
		System.out.println("m = " + m + "  n = " + n + "  t = " + t);
	}

}
输出:

发生异常:For input string: "ab85"
m = 8888  n = 123  t = 666




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值