抽象类与接口

1.定义一个接口,其中包含一个displa()方法用于显示信息:通知类,汽车类,广告类,均要实现该接口显示“通知内容”,“汽车油量”和“广告信息”。

程序代码:

public class exe {

		interface Shape{
			 void display();
		}
		 static class Message implements Shape{
			public void display(){
				System.out.println("通知内容");
		}}
		 static class Gas implements Shape{
				public void display() {
					System.out.println("汽车油量");
		}}
		 static class Adv implements Shape{
			 public void display() {
				 System.out.println("广告信息");
		}}
		 public static void main(String[] args){
			Message a=new Message();
			a.display();
			Gas b=new Gas();
			b.display();
			Adv c=new Adv();
			c.display();
		}}

 

2.定义接口Shape,其中包括一个方法size(),设计矩形,圆,圆柱体等类实现Shape接口,然后用size()方法求各个图像面积并输出。

 

程序代码:

public class exx {
interface Shape{
	double size();
}
static class Rac implements Shape{ 
	double a,b;
	public Rac(double a,double b){
		this.a=a;
		this.b=b;
	}
	public double size(){
		return a*b;
	}
static class Cir implements Shape{
		double r;
		public Cir(double r){
			this.r=r;
		}
		public double size(){
			return Math.PI*r*r;
	
		
}
static class CC implements Shape{
			double r,h;
			public CC(double r,double h){
				this.r=r;
				this.h=h;
			}
			public double size(){
				return Math.PI*r*r*h;
			}
	
public static void main(String[] args){
	Shape[] s=new Shape[3];
	s[0]=new Rac(3,5);
	System.out.println("矩形的面积为:"+s[0].size());
	s[1]=new Cir(6);
	System.out.println("圆的面积为:"+s[1].size());
	s[2]=new CC(4,8);
	System.out.println("圆柱的面积为:"+s[2].size());
}	
}
}	
}
}

 

3.定义一个抽象类——水果,其中包括getweight()方法,分别创建苹果,桃子,橘子类,创建的对象存放在一个水果类型的数组中,输出数组中所有水果的类型,重量。

 

程序代码:

abstract class Fruit{
		abstract double getWeight();
	}
class  Apple extends Fruit{
		double w1;
		String t1;
		 Apple(double w11,String t11){
			w1=w11;
			t1=t11;
		}
		public double getWeight(){
			return w1;
		}
	  }
 class Orange extends Fruit{
			double w2;
			String t2;
			public Orange(double w22,String t22){
				t2=t22;
				w2=w22;
			}
			public double getWeight(){
				return w2;
			}
	}
class Peach extends Fruit{
			double weight;
			String type;
			public Peach(double weigh,String typ){
				type=typ;
				weight=weigh;
			}
			public double getWeight(){
				return weight;
			}
	}
	public class eex {
	public static void main(String[] args){
		Fruit f[]=new Fruit[3];
		f[0]=new Apple(30,"苹果");
		f[1]=new Orange(22,"橙子");
		f[2]=new Peach(43,"桃子");
		for(int i=0;i<3;i++){	
		System.out.println(f[i].getWeight());
		System.out.println(f[i].getClass().getName());
	}
	}
	}

 

 
  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值