`
msn877763580
  • 浏览: 81165 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

抽象类与接口

 
阅读更多

抽象类视频学习代码记录:

首先定义一个抽象类及两个实现类

abstract class Shape{
	public abstract int computeArea();//计算形状面积
}

class Triangle extends Shape{	
	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 this.width * this.height;
	}
}

 然后定义一个测试类,可以很容易看出,测试类中应用到了多态的知识。

public class AbstractTest {
	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);
	}
}

 通过上面的例子可以看出抽象类的作用:

1.通过继承实现多态,后期绑定,为将来要实现的东西做好接口,实现重用性。
2.接口就是更纯粹的抽象类

还可以帮助我们认识到:多态就是在运行时表现的多种形态。

下面通过一个简单的小例子学习一下接口以及接口中对于多态的应用

package cn.sisy.inter;

public class InterfaceTest {
	public static void main(String[] args) {
		A a = new B();
		a.output();
		
		B b = (B)a ;
		b.output();
	}
}
interface A{
	public void output();
}


class B implements A{
	public void output(){
		System.out.println("B");
	}
}

 程序运行结果:

 B
 B

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics