抽象类与接口的练习

1 定义一个ClassName接口,接口中只有一个抽象方法,设计一个类Company,该类实现接口ClassName中的方法getClassName(),功能是获取该类方法的名称;编写应用程序使用Company类
1)ClassName接口

interface ClassName{
 public abstract String getClassName();
}

2)Company 类

class Company implements ClassName {
 @Override
 public String getClassName() {
  System.out.println("该类的名称为:");
  return "Company";
 }
}

2 定义一个IUSB接口 ,接口中有两个抽象方法,设计类keyboard print 来实现ClassName中的public abstract boolean check 和 public abstract void work两个方法 设计一个Computer类
定义一个使用keyboard和print的方法
1)IUSB接口

interface IUSB{
	public abstract boolean check();
	public abstract void work();
}

2)Computer类

class Computer{
	public void use(IUSB usb) {
		if(usb.check())
			usb.work();
		else 
			System.out.println("设备出现故障无法使用!");
	}
}

3)keyboard类

class keyboard implements IUSB{
	@Override
	public  boolean check(){
		return true;
	}
	public void work() {
		System.out.println("设备正在使用中!");
	}
}

4)print类

class print implements IUSB{
	@Override
	public boolean check() {
		return false;
	}
	public void work() {
		System.out.println("设备正在使用中!");
	}
}

5)主方法

	public static void main(String [] args) {
		Computer com = new Computer();
		com.use(new print());
		com.use(new keyboard());

3 定义类Shape,用来表示一般二维图形。Shape具有抽象方法area()和perimeter(),分别用来计算形状的面积和周长。试定义一些二维形状类(如矩形rectangle,三角形triangle,圆形circular等),这些类均为Shape的子类
1)Shape类

abstract class Shape{
	public abstract void area();
	public abstract void perimeter();
}

2)矩形类

class Rectangle extends Shape{
	 double length;
	 double width;
	 public Rectangle(double length,double width) {
		 this.length = length;
		 this.width = width;
	 }
	@Override
	public void area() {
		System.out.println("矩形的面积大小为:"+this.length*this.width);
	}
	@Override
	public void perimeter() {
		System.out.println("矩形的周长大小为:"+2*(this.length+this.width));
	}
}

3)三角形类

class Triangle extends Shape {
	double bottom;
	double heigth;
	public Triangle(double bottom,double heigth) {
		this.bottom = bottom;
		this.heigth = heigth;
	}
	@Override 
	public void area() {
		System.out.println("三角形的面积为:"+0.5*this.bottom*this.heigth);
	}
	@Override 
	public void perimeter() {
		System.out.println("已知底和高求不出三角形的周长");
	}
}

4)圆形

class Circula extends Shape{
	double r;
	
	public Circula(double r) {
		this.r = r;
	}
	@Override 
	public void area() {
		System.out.println("圆形的面积为:"+Math.round(0.5*this.r*this.r*Math.PI));
	}
	@Override 
	public void perimeter() {
		System.out.println("圆形的周长为:"+Math.round(Math.PI*this.r));
	}
}

5)主方法

	public static void main(String [] args) {
		Shape re = new Rectangle(12,5);
		Shape tr = new Triangle(6,6);
		Shape ci = new Circula(4);
		System.out.println("矩形:");
		re.area();
		re.perimeter();
		System.out.println("三角形:");
		tr.area();
		tr.perimeter();
		System.out.println("圆形:");
		ci.area();
		ci.perimeter();
    }

你可能感兴趣的:(Java,抽象类)