初学者。
匿名类是一个子类,没有类名,用匿名类创建对象时,要直接使用父类的构造方法。
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