5、小慕的祖传秘方 老师您检查下这题 对不对呢 感觉不太清楚
来源:11-14 测评作业

unbreakable_全栈
2024-11-30
package com.imooc.family;
public class Family {
public String name;
public String secretRecipe;
public Family(String name, String secretRecipe) {
this.name = name;
this.secretRecipe = secretRecipe;
}
// 受保护的方法,只有家族成员可以访问
protected String getSecretRecipe() {
return secretRecipe;
}
@Override
public String toString() {
return "家族成员: " + name + ", 秘方: " + getSecretRecipe();
}
}
package com.imooc.family;
public class XiaoMuFamily extends Family {
public XiaoMuFamily(String name, String secretRecipe) {
super(name, secretRecipe);
}
// 公共方法,只有小慕叔叔家族成员可以访问秘方
public String getFamilySecretRecipe() {
return getSecretRecipe();
}
// 重写toString方法,显示家族成员和秘方
@Override
public String toString() {
return "小慕家族成员: " + name + ", 秘方: " + getSecretRecipe();
}
}
package com.imooc.family;
public class XiaoMuUncleFamily extends Family {
public XiaoMuUncleFamily(String name, String secretRecipe) {
super(name, secretRecipe);
}
// 公共方法,只有小慕叔叔家族成员可以访问秘方
public String getFamilySecretRecipe() {
return getSecretRecipe();
}
// 重写toString方法,显示家族成员和秘方
@Override
public String toString() {
return "小慕叔叔家族成员: " + name + ", 秘方: " + getSecretRecipe();
}
}
package com.imooc.family;
public class LaoWangFamily {
private String name;
private String secretRecipe; // 假设这个秘方不是祖传秘方,或者即使它是,老王家也不能访问
public LaoWangFamily(String name, String secretRecipe) {
this.name = name;
this.secretRecipe = secretRecipe;
}
@Override
public String toString() {
// 注意:这里不调用 getSecretRecipe(),因为我们假设老王家不能访问小慕家族的秘方
return "隔壁老王家族成员: " + name;
}
}
package com.imooc.family;
public class FamilyTest {
public static void main(String[] args) {
Family xiaoMu = new XiaoMuFamily("小慕", "祖传秘方");
Family xiaoMuSon = new XiaoMuFamily("小慕的儿子", "祖传秘方");
Family xiaoMuUncle = new XiaoMuUncleFamily("小慕叔叔", "祖传秘方");
Family xiaoMuUncleSon = new XiaoMuUncleFamily("小慕叔叔的儿子", "祖传秘方");
LaoWangFamily laoWang = new LaoWangFamily("老王", "隔壁老王的秘方");
LaoWangFamily xiaoMuBrother = new LaoWangFamily("小慕哥哥", "隔壁老王的秘方");
System.out.println(xiaoMu);
System.out.println(xiaoMuSon);
System.out.println(xiaoMuUncle);
System.out.println(xiaoMuUncleSon);
System.out.println(laoWang);
System.out.println(xiaoMuBrother);
}
}
写回答
1回答
-
彭彭老师
2024-12-01
同学的理解有些偏差,可参考下面的思路再理解一下
1、创建 3 个包,分别表示小慕叔叔家、小慕家、隔壁老王家
2、类与包的所属关系如下图
3、子类与父类之间的继承关系如下图(小慕家族直接或间接继承小慕爷爷)
4、使用 protect 关键字修饰小慕爷爷的秘方,所有直接继承人或间接继承人均可以访问秘方,无论是否同包都可以访问
5、隔壁老王与小慕爷爷没有继承关系,不能使用秘方
package com.imooc.xiaomu; public class Grandpa { private String secretRecipe = "慕氏秘方"; // 药方 /** * 获取药方 */ protected void showSecretRecipe() { System.out.println("小慕家的祖传秘方 - " + secretRecipe); } }
00
相似问题
array的作业,请老师您检查下
回答 1
实战项目
回答 2