码迷,mamicode.com
首页 > 其他好文 > 详细

类的继承和组合

时间:2014-11-29 12:00:51      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:类的继承和组合

类的继承
public class Fruit{
public double weight;
public void info(){
System.out.println("水果"+weight);
}
}
public class Apple extends Fruit{
public static void main(String[] args){
//创建Apple对象
Apple apple=new Apple();
//Apple对象本身没有weight成员变量
//因为Apple的父类有weight成员变量,也可以访问Apple对象的weight成员变量
a.weight=90;
//调用Apple对象的info()方法
a.info();
}
}


public class Bird{
//Bird类的fly()方法
public void fly(){
System.out.println("fly");
}
}


public class Os extends Bird{
//重写Bird类的fly()方法
public void fly(){
System.out.println("fly1");
}
public static void main(String[] args){
//创建Os对象
Os o=new Os();
//执行Os对象的fly()方法
o.fly();
}
}
//可以使用super(被覆盖的是实例方法,或者父类类名(被覆盖的是类方法))作为调用者来调用被覆盖的方法
如果父类方法具有private访问权限,则该方法对其子类是隐藏的,因此子类无法访问该方法
class Animal{
private void beat(){
System.out.println("beat");
}
public void breathe(){
beat();
System.out.println("breathe");
}
}
//继承Animal,直接复用父类的breathe()方法
public Bird extends Animal{
public void fly(){
System.out.println("fly");
}
}
//继承Animal,直接复用父类的breathe()方法
public Wolf extends Animal{
public void run(){
System.out.println("run");
}
}
public class InheritTest{
public static void main(String[] args){
Bird b=new Bird();
b.breathe();
b.fly();
Wolf w=new Wolf();
w.breathe();
w.run();
}
}
class Animal{
private void beat(){
System.out.println("beat");
}
}
public void breath(){
beat();
System.out.println("breathe");
}
}
class Bird{
//将原来的父类组合到原来的子类,作为子类的一个组合成分
private Animal a;
public Bird(Animal a){
this.a=a;
}
//重新定义一个自己的breathe()方法
public void breathe(){
//直接复用Animal提供的breathe()方法来实现Bird的breathe()方法
a.breathe();
}
public void fly(){
System.out.println("fly");
}
}
class Wolf{
...
}
public class CompositeTest{
public static void main(String[] args){
//此时需要显示创建被组合的对象
Aniaml animal=new Animal();
Bird b=new Bird(a);
b.breathe();
b.fly();
//此时需要显示创建被组合的对象
Aniaml animal1=new Animal();
Wolf w=new Wolf(animal1);
w.breathe();
w.run();
}
}

类的继承和组合

标签:类的继承和组合

原文地址:http://blog.csdn.net/hephec/article/details/41592901

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!