1、运行结果是什么
public class TestA {
void fun1(){
System.out.println(fun2());
}
int fun2(){
return 12;
}
}
public class TestB extends TestA{
int fun2(){
return 34;
}
public static void main(String[] args) {
TestA a;
TestB b = new TestB();
a=b;
a.fun1();
}
}
结果:34
解释:子类可以继承的父类成员方法,如果在子类中出现了同名称的成员方法,则称为覆盖,即子类的成员方法会覆盖掉父类的同名成员方法。如果要在子类中访问父类中同名成员方法,需要使用super关键字来进行引用。
2、建立一个图形接口,声明一个面积函数。圆形和矩形都实现这个接口,并得出两个图形的面积
注:体现面向对象的特征,对数值进行判断,用异常处理,不合法的数值要出现“这个数值是非法的”提示,不再进行运算。
public interface Area {
public abstract double getArea();//可以省略 public abstract 修饰符
}
public class NotValueException extends RuntimeException { //自定义异常
NotValueException(){
super();
}
NotValueException(String message){
super(message);
}
}
public class Circle implements Area {
private double radius;
private static final double PI = 3.14;
Circle(double radius){
this.radius=radius;
}
public double getArea() {
if(radius<=0)
throw new NotValueException("这个数值是非法的");
return PI * radius*radius;
}
}
public class Rectangle implements Area {
private double length,width;
Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public double getArea() { //(double length,double width)
if(length<=0 || width<=0)
throw new NotValueException("这个数值是非法的");
return length*width;
}
}
public class Areable {
public static void main(String[] args) {
Circle c = new Circle(-3);
Rectangle rec = new Rectangle(3.1,4.5);
System.out.println(c.getArea());
System.out.println(rec.getArea());
}
}