public class Test {
int area = shape.computeArea();
System.out.println("triangle:"+area);
shape = new Rectangle(10,10);
area = shape.computeArea();
System.out.println("rectangle:"+ area);
}
}
abstract class Shape {//使用了 abstract关键字修饰的类叫做抽象类,抽象类无法实例化,也就是说不能new出来一个抽象类的对象
class Triangle extends Shape {//在子类继承父类(前提父类是个抽象类)的情况下,那该子类必须要实现父类中所定义的所有抽象方法;否则该子类需要声明成一个abstract class
int width;
int height;
this.height = height;
}
public int computeArea() {
return (width*height) / 2;
}
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle(int width,int height) {
this.width = width;
this.height = height;
}
public int computeArea() {
return width*height;
}
}
public static void main(String[] args) {
int area = shape.computeArea();
System.out.println("triangle:"+area);
shape = new Rectangle(10,10);
area = shape.computeArea();
System.out.println("rectangle:"+ area);
}
}
abstract class Shape {//使用了 abstract关键字修饰的类叫做抽象类,抽象类无法实例化,也就是说不能new出来一个抽象类的对象
public abstract int computeArea();//计算形状面积、使用abstract关键字修饰的方法叫做抽象方法,抽象方法只有声明没有实现。
public void change() {//抽象类中也可以包含具体方法
}
//如果一个类中包含了抽象方法,那么这个类一定要声明成abstract class,也就是说,该类一定是抽象类。
}class Triangle extends Shape {//在子类继承父类(前提父类是个抽象类)的情况下,那该子类必须要实现父类中所定义的所有抽象方法;否则该子类需要声明成一个abstract class
int width;
int height;
public Triangle(int width,int height) {//构造方法主要完成变量的初始化
this.height = height;
}
public int computeArea() {
return (width*height) / 2;
}
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle(int width,int height) {
this.width = width;
this.height = height;
}
public int computeArea() {
return width*height;
}
}