java练习课

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


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());
	}

}


你可能感兴趣的:(java,练习)