Java面对对象

本文展示了Java编程中的多态性概念,包括方法的重载和重写。通过创建`database`父类及其`CD`和`DVD`子类,演示了如何在子类中添加特性和覆盖父类方法。此外,还讨论了一个面积计算的示例,`Rectangle`类用于计算面积,而`Rectangular`子类则扩展了面积计算以计算体积。
摘要由CSDN通过智能技术生成

一.多态:
1.重载:一个类中具有相同的方法名,但这些方法的参数和个数不同。

注意: 同一个类中方法名相同,参数列表不同。 返回值类型不能用于区分方法的重载。
2.重写:子类包含和父类同名的方法。 方法的重写应该要遵循“两同两小一大”规则。
3.注意: 构造方法不能被继承。 构造函数不能被重写。

二.作业
1.创建database父类,创建CD和DVD子类,并且CD子类增加artist特色,DVD子类增加director特色,最后用print方法输出。

package com.chapter2;

public class database {
	String title;
	int playtime;
	String isBrrow;
	
	public database(String title,int playtime,String isBrrow){
		this.title = title;
		this.playtime=playtime;
		this.isBrrow=isBrrow;
	}
	
	public void print(){
		System.out.printf("标题:%s\t播放时间:%d\t是否外借:%s\n",title,playtime,isBrrow);
	}
}
package com.chapter2;

public class CD extends database {
	String artist;
	public CD(String title,int playtime,String isBrrow,String artist){
		super(title,playtime,isBrrow);
		this.artist=artist;
	}
	public void print(){
		System.out.printf("标题:%s\t艺术家:%s\t播放时间:%d\t是否外借:%s\n",title,artist,playtime,isBrrow);
	}
}
package com.chapter2;

public class DVD extends database {
	String director;
	public DVD(String title,int playtime,String isBrrow,String director){
		super(title,playtime,isBrrow);
		this.director=director;
	}
	public void print(){
		System.out.printf("标题:%s\t导演:%s\t播放时间:%d\t是否外借:%s\n",title,director,playtime,isBrrow);
	}
}
package com.chapter2;

public class Test {
	public static void main(String[] args) {
		database cd1= new CD("起风了",3,"是","辣椒");
		database cd2= new CD("上号",3,"是","把门那样");
		cd1.print();
		cd2.print();
		database dvd1= new DVD("一出好戏",3,"否","黄渤");
		dvd1.print();
	}
}

2.创建面积父类,里面有长和宽变量,在面积类中用长、宽计算面积。
创建体积子类,里面有高变量,继承面积父类,计算体积。

package com.chapter3;

public class Rectangle {
	int l;
	int w;
	public Rectangle(int l,int w){
		this.l=l;
		this.w=w;
	}
	public int getArea(){
		return l*w;
	}
}
package com.chapter3;

public class Rectangular extends Rectangle {
	int h;
	public Rectangular(int l,int w,int h){
		super(l,w);
		this.h=h;
	}
	public int getVolume(){
		return l*w*h;
	}
}
package com.chapter3;

public class Test {
	public static void main(String[] args) {
		Rectangle le = new Rectangle(12,3);
		System.out.println("长方形的面积:"+le.getArea());
		Rectangular ular = new Rectangular(12,3,4);
		System.out.println("长方体的面积:"+ular.getVolume());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值