请高人为我解释一下public class Task1 {public static void main(String[] args) {B b = new B(5,2);b.calc();System.out.println(b.getP());}}public class A {protected int k = 0;public A(int x) {k = x;}public void calc(){k = k + 1;System.out.println("A: " + k);}}public class B extends A {protected int m;public B(int p, int q){super(q);this.m = p;}public void calc() {if(m % 2 == 0) {super.calc();}else {k *= 2;System.out.println("B: " + k);}}public int getP(){return k;}}
1 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
public class Task1 {
public static void main(String[] args) {
//创建B的实例
B b = new B(5, 2);
//调用calc,这里m = 5 , k = 2; 所以运行calc的else部分
b.calc();
System.out.println(b.getP());
}
}
class A {
//protected修饰符,标明k能被子类继承
protected int k = 0;
//带参构造函数
public A(int x) {
k = x;
}
public void calc() {
k = k + 1;
System.out.println("A: " + k);
}
}
class B extends A {
//继承父类的k属性,和clac函数
protected int m;
public B(int p, int q) {
//调用父类构造函数, 这里就给k赋值
super(q);
this.m = p;
}
//重写负类的calc函数
public void calc() {
if (m % 2 == 0) {
super.calc();
} else {
k *= 2;
System.out.println("B: " + k);
}
}
public int getP() {
return k;
}
}
这样应该懂了吧
添加回答
举报
0/150
提交
取消