Java杂谈之接口和继承的经典案例
2014-08-12 18:48
357 查看
以下是关于接口和的一个经典案例。
包含Shape接口(形状),Point类(点),Circle类(圆),Column类(圆柱),Test类(测试)
一些注意点和知识在其中的注释中已经说明了,就不额外赘述了。
1.Shape接口:
2.Point类:
3.Circle类:
4.Column类:
5.Test类:
6.结果截图:
包含Shape接口(形状),Point类(点),Circle类(圆),Column类(圆柱),Test类(测试)
一些注意点和知识在其中的注释中已经说明了,就不额外赘述了。
1.Shape接口:
package JavaInterface; public interface Shape { public abstract double area(); public abstract double volume(); public abstract String getName(); }
2.Point类:
package JavaInterface; public class Point implements Shape { private int x; private int y; public Point() { this.x = 0; this.y = 0; } public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public double area() { // TODO Auto-generated method stub return 0; } @Override public double volume() { // TODO Auto-generated method stub return 0; } @Override public String getName() { // TODO Auto-generated method stub return "点:[" + this.x + "," + this.y + "]"; } }
3.Circle类:
package JavaInterface; public class Circle extends Point implements Shape { private int r; public Circle() { this.r = 0; } public Circle(int x, int y, int r) { super(x, y); this.r = r; } @Override public double area() { return Math.PI * r*r; } @Override public String getName() { return "圆:半径=" + this.r; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
4.Column类:
package JavaInterface; public class Column extends Circle { private int h; public Column() { this.h = 0; } public Column(int x, int y, int r, int h) { super(x, y, r); this.h = h; } @Override public String getName() { return "圆柱:高度=" + this.h; } @Override public double area() { return super.area() * 2 + 2 * Math.PI * h * super.getR(); } @Override public double volume() { return super.area() * h; } }
5.Test类:
package JavaInterface; public class Test { public static void main(String[] args) { //圆 //将对象的引用定义为接口,即面向接口的编程 Shape sc = new Circle(2,4,8); Circle c = new Circle(2,4,8); System.out.println("类型:"+c.getName()); System.out.println("面积:"+c.area()); System.out.println("体积:"+c.volume()); //圆柱 Column col = new Column(2,4,8,2); System.out.println("类型:"+col.getName()); System.out.println("面积:"+col.area()); System.out.println("体积:"+col.volume()); } }
6.结果截图:
相关文章推荐
- 黑马程序员——Java基础--继承、多态、抽象、接口联合使用的案例
- java基础案例:继承父类并实现接口
- Java语言接口与继承本质( 很经典)
- java 接口回调经典案例--网络请求回调
- JAVA学习心得--继承、接口与泛型
- 澄清Java语言接口与继承的本质
- 澄清Java语言接口与继承的本质
- 澄清Java语言接口与继承的本质(选择自 legendinfo 的 Blog)
- 澄清Java语言接口与继承的本质
- Java杂谈(七)--接口& 组件、容器
- JAVA中如何用接口实现多继承和多态 (非常好)
- JAVA如何利用接口制造类似于C++的多继承
- 澄清Java语言接口与继承的本质
- 澄清Java语言接口与继承的本质
- java面向对象浅析系列2——抽象类、接口与多继承
- JAVA中几个易混淆关键词的理解:行为,隐藏,组合和继承,覆写和重载,多形(多态)性,动态绑定,上溯造型,抽象类,接口
- java面向对象浅析系列2——抽象类、接口与多继承
- 澄清Java语言接口与继承的本质z
- 澄清Java(一)----接口与继承
- 温习Java笔记(1):经典案例深刻认识java实体