亲宝软件园·资讯

展开

Java抽象类和接口的区别

海拥 人气:0

1、抽象类 vs 接口 

import java.io.*;

abstract class Shape {

	String objectName = " ";

	Shape(String name) { this.objectName = name; 

        }

	public void moveTo(int x, int y){

		System.out.println(this.objectName + " "

						+ "已移至"

						+ " x = " + x + " and y = " + y);

	}

	abstract public double area();

	abstract public void draw();

}



class Rectangle extends Shape {

	int length, width;

	Rectangle(int length, int width, String name){

		super(name);

		this.length = length;

		this.width = width;

	}

	@Override public void draw(){

		System.out.println("矩形已绘制");

	}

	@Override public double area(){

		return (double)(length * width);

	}

}



class Circle extends Shape {

	double pi = 3.14;

	int radius;

	Circle(int radius, String name){

		super(name);

		this.radius = radius;

	}

	@Override public void draw(){

		System.out.println("圆形已绘制");

	}

	@Override public double area(){

		return (double)((pi * radius * radius) / 2);

	}

}



class HY {

	public static void main(String[] args){

		Shape rect = new Rectangle(2, 3, "Rectangle");

		System.out.println("矩形面积:"

						+ rect.area());

		rect.moveTo(1, 2);

		System.out.println(" ");

		Shape circle = new Circle(2, "Circle");

		System.out.println("圆的面积:"

						+ circle.area());

		circle.moveTo(2, 4);

	}

}

输出:

矩形面积:6.0

矩形已移至 x = 1 和 y = 2

圆的面积:6.28

圆已移至 x = 2 和 y = 4

如果我们在矩形和圆形之间没有任何通用代码,请使用界面。

import java.io.*;

interface Shape {

	void draw();

	double area();

}

class Rectangle implements Shape {

	int length, width;

	Rectangle(int length, int width){

		this.length = length;

		this.width = width;

	}

	@Override public void draw(){

		System.out.println("矩形已绘制");

	}

	@Override public double area(){

		return (double)(length * width);

	}

}

class Circle implements Shape {

	double pi = 3.14;

	int radius;

	Circle(int radius) { this.radius = radius; }



	@Override public void draw(){

		System.out.println("圆形已绘制");

	}



	@Override public double area(){

		return (double)((pi * radius * radius) / 2);

	}

}

class HY {

	public static void main(String[] args){

		Shape rect = new Rectangle(2, 3);

		System.out.println("矩形面积:"

						+ rect.area());

		Shape circle = new Circle(2);

		System.out.println("圆的面积:"

						+ circle.area());

	}

}

输出:

矩形面积:6.0

圆的面积:6.28

什么时候用什么?

如果以下任何陈述适用于您的情况,请考虑使用抽象类:  

如果以下任何陈述适用于您的情况,请考虑使用接口:  

加载全部内容

相关教程
猜你喜欢
用户评论