java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java抽象类和接口的区别

Java抽象类和接口的区别详情

作者:海拥

这篇文章主要介绍的是Java抽象类和接口的区别详情,

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

什么时候用什么?

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

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

到此这篇关于Java抽象类和接口的区别详情的文章就介绍到这了,更多相关Java抽象类和接口的区别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文