为什么在编译以下的代码时输出结果为 B:4

请高人为我解释一下
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;
}
}

不负相思意
浏览 100回答 1
1回答

侃侃尔雅

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;}}这样应该懂了吧
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
CSS3