在生活中,不可能一个类组成一个方法,比如汽车坏了,是需要送到修理厂的;电视机,电脑坏了,也是需要找一个器修厂的。Java中也是一样的,一个类对应的只是一项内容,因此,Java中有时候会需要多个类来共同操作。
下面的代码就是多类使用的案例:代码中涌动了有参构造函数和无参构造函数,
package qianfeng;
class DianNao1{//定义了一个电脑类
String screen;
String keyboard;//成员变量
public DianNao1() {
screen = null;
keyboard = null;
}//无参构造方法,初始化变量
public DianNao1(String s,String k) {
screen = s;
keyboard = k;
}//有参构造方法
public void working() {
if (screen != null) {
System.out.println("电脑运行正常");
}else {
System.out.println("电脑出现故障");
}
}
}
class DianShi{
String screen;
String controller;
public DianShi() {}
public DianShi(String s,String c) {
screen = s;
controller = c;
}
public void watching() {
if(controller !=null) {
System.out.println("电视运行正常");
}else {
System.out.println("电视出现故障");
}
}
}
class Factory{
String name;
String address;
String telephone;
public Factory(String n,String a,String t) {
name = n;
address = a;
telephone = t;
}
public void repairDianShi(DianShi ds) {
if(ds.controller == null) {
System.out.println("电视已修好");
ds.controller = "null";
}else {
System.out.println("电视并没有问题");
}
}
public void repairDianNao1(DianNao1 dn) {
if (dn.screen == null) {
System.out.println("电脑已修好");
dn.screen = "null";
}else {
System.out.println("电脑没有问题");
}
}
}
public class DianNao {
public static void main(String[] args) {
DianNao1 dell = new DianNao1("AOC", "双飞燕");
DianShi mi = new DianShi("SHAPP", "Apple");
Factory f= new Factory("磊哥电器维修十年老店", "迪拜塔顶层", "88888888");
for(int i = 0;i < 5; i ++) {
dell.working();
}
dell.screen = null;
dell.working();
f.repairDianNao1(dell);
dell.working();
for (int i = 0; i <5; i ++) {
mi.watching();
}
mi.controller = null;
mi.watching();
f.repairDianShi(mi);
mi.watching();
}
}