练习1 手机
base:
public class Handset { public String brand; public String type; public void sendInfo(){ System.out.println("发送短信.");} public void call(){ System.out.println("拨打电话.");} public void info(){ System.out.println("收取短信");} public void toStringInfo(){ sendInfo();call();info();}}
interface:
public interface Network { void networkConn();}
public interface PlayWiring { void play(String content);}
public interface TheakePictures { void takePictures();}
实现类_智能手机:
public class AptitudeHandset extends Handset implements TheakePictures, Network, PlayWiring { public void play(String content) { System.out.println("智能播放" + content + "."); } public void networkConn() { System.out.println("上网."); } public void takePictures() { System.out.println("拍照."); } public void toStringInfo() { System.out.println("智能手机能:"); String content = "音频内容"; super.toStringInfo(); play(content); networkConn(); takePictures(); } public static void main(String[] args) { AptitudeHandset iphone4 = new AptitudeHandset(); iphone4.toStringInfo(); } }
输出结果:
智能手机能:
发送短信.
拨打电话.
收取短信
智能播放音频内容.
上网.
拍照.
这里发现一个父类指向子类对象的问题:
父类 a = new 子类
那么对象a所调取的方法,是父类所含的方法,如果子类有对此方法进行重写的话,会调取子类的重写方法,但是,子类所特有的方法无法被调取(即父类没有此方法).它的精髓所在,这样就可以做到只关注父类所包含的方法,而利用子类进行优化,而子类可以多继承,所以换子类成本很低,不需要动到父类.举个例子:如练习1,手机是父类,它包含通话,发短信.智能手机,与普通手机是子类.所以 手机 a = new 智能手机 ,智能手机可以重写通话,重写成智能手机具备的特性,利用网络通话,未来智能手机可能利用手表通话,这个时候只要变动子类即可.
//-----------------------------------华丽丽的分割线--------------------------------------------------------------------------
实现类_普通手机:
public class CommonHandset extends Handset implements PlayWiring { public void play(String content) { System.out.print("播放" + content); } public void toStringInfo() { System.out.println("普通手机能:"); super.toStringInfo(); play("音频内容"); } public static void main(String[] args) { CommonHandset phone = new CommonHandset(); phone.toStringInfo(); } }
输出结果:
普通手机能:
发送短信.
拨打电话.
收取短信
播放音频内容