类的继承和组合

类的继承
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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值