Java 中 抽象 特性的应用

原文地址:

http://www.5ixiudou.com/portal/detailInfo/1000000005/217

抽象,是指把一些不同类型的物体的共有属性或者行为抽取出来,然后构成一个公共的父类。然后当使用这些公共的属性或者行为的使用,就可以通过父类去调用,这样的话,就不用去考虑具体应该由谁去调用这个行为,屏蔽了类型的细节,用起来更方便。废话不多说,直接上代码:

package cn.cttic.staffcert.cert.service;

 

//定义形状类

public abstract class Graphics {

//计算面积

public abstract double getGirth(Graphics g);

public static void main(String[] args) {

//注意,在使用时,要先向上类型转换,然后父类对象进行调用时,自动调用相应子类类型的方法

//计算三角形面积

Graphics g = new Triangle (3,4,5);

double area = g.getGirth(g);

System.out.println(area);

//计算圆形面积

Graphics gC = new Circle(2);

double areaC = gC.getGirth(gC);

System.out.println(areaC);

}

}

 

//定义三角形类,继承自形状类

class Triangle extends Graphics {

public Triangle(float longValue ,float widthValue ,float heightValue){

this.longValue = longValue;

this.widthValue = widthValue;

this.heightValue = heightValue;

}

 

private float longValue;

private float widthValue;

private float heightValue;

//实现公共方法

@Override

public double getGirth(Graphics g){

return longValue + widthValue + heightValue ;

}

}

 

//定义圆形类,继承自形状类

class Circle extends Graphics {

private float r;

public Circle (float r){

this.r = r;

}

//实现公共方法

@Override

public double getGirth(Graphics g){

return Math.PI * r * 2 ;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值