Java面向对象
第三章 继承与多态
包是类的逻辑组织形式。在程序中可以申明类所在的包。同一个包中类名不能重复。通过包可以对类的访问权限进行控制。此外包是有层级结构,即一个包可以包含多个子包
package < 包名>
注意!!!
申明一个包的语句必须写在类中的第一行
实例:
package com. java. oriented. dato. figure ;
public class Hero {
}
包的导入
如果要是用java中存在的包,可以使用import语句导入包,格式如下
import < 包名> . <类名>
如果要导入一个包中多个类,可使用“ * ” 表示包中所有类,格式如下
import java. util. * ;
import java. util. ArrayList ;
继承
继承是面向对象程序设计的一个重要特征,它是通过继承原有类派生出的子类进而构造出更为复杂的子类。子类既有新定义的行为特征,又有原有类的行为特征。
语法如下所示:
[ 修饰符] class 子类名 [ extends 父类名] {
}
在使用继承特性时,需要注意的是,子类可以继承父类中访问权限为public , protected , default
的成员变量和方法
多态
多态是指同一种操作作用于不同的对象,可以有不同的解释,以至于产生不同的执行结果。在编译时,可以通过父类的指引指向子类对象,而在运行时,则通过父类指向子类对象,调用子类中重写父类的方法。
例子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 ( ) ) ;
}
}