java--抽象类、抽象方法

public class Test {

public static void main(String[] args) {


Shape shape = new Triangle(10,6);

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.width = width;//方法参数赋给了成员变量
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;


}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值