首页 技术 正文
技术 2022年11月9日
0 收藏 689 点赞 2,789 浏览 1318 个字
 //Java中的继承和组合之间的联系和区别
//本例是继承 class Animal
{
private void beat()
{
System.out.println("心胀跳动...");
}
public void breath()
{
beat();
System.out.println("吸一口气,吐一口气,呼吸中...");
}
}
//继承Animal,直接复用父类的breath()方法
class Bird extends Animal
{
public void fly()
{
System.out.println("我在天空自由飞翔...");
}
}
//继承Animal,直接复用父类breath()方法
class Wolf extends Animal
{
public void run()
{
System.out.println("我在陆地上快速奔跑...");
}
}
public class InheritTest
{
public static void main(String[] args)
{
Bird b = new Bird();
b.breath();
b.fly();
Wolf w = new Wolf();
w.breath();
w.run();
}
}
 //Java中的继承和组合之间的联系和区别
//本例是组合
class Animal
{
private void beat()
{
System.out.println("心胀跳动...");
}
public void breath()
{
beat();
System.out.println("吸一口气,吐一口气,呼吸中...");
}
}
class Bird
{
//将原来的父类组合到子类中来,作为子类的一个组合部分.
private Animal a;
public Bird(Animal a)
{
this.a = a;
}
//重新定义一个自己的breath()方法
public void breath()
{
//直接复用Animal提供的breath()方法来实现Bird的breath()方法
a.breath();
}
public void fly()
{
System.out.println("我在天空自在的飞翔...");
}
}
class Wolf
{
//将原来的父类组合到子类中来,作为子类的一个组合部分.
private Animal a;
public Wolf(Animal a)
{
this.a = a;
}
//重新定义一个自己的breath()方法
public void breath()
{
//直接复用Animal提供的breath()方法来实现Bird的breath()方法
a.breath();
}
public void run()
{
System.out.println("我在陆地上快速奔跑...");
}
} public class CompositeTest
{
public static void main(String[] args)
{
//此时需要显示创建被组合的对象
Animal a = new Animal();
Bird b = new Bird(a);
b.breath();
b.fly(); //此时需要显示创建被组合的对象
Animal a2 = new Animal();
Wolf w = new Wolf(a2);
w.breath();
w.run();
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289