解释下面这段代码class FatherA{ int x,y; FatherA(int x,int y){this.x=x;this.y=y;} static void show(){ System.out.println("FatherA静态方法"); } void compare(){ System.out.println(x+y); } } class SonB extends FatherA{ int x,y; SonB(int x,int y) { super(x,y);//代码1 this.x=x; this.y=y; } void compare(){ System.out.println(x+y); } static void show(){ System.out.println("SonB类的静态方法"); } } public class Test { public static void main(String[] args) { FatherA a; SonB b=new SonB(10,20); a=b; b.compare();//代码2 a.compare();//代码3 b.show();//代码4 a.show();//代码5 } }
时间: 2023-12-06 10:41:33 浏览: 32
这段代码定义了一个父类 FatherA 和一个子类 SonB,其中 SonB 继承自 FatherA。在 main 方法中,创建了一个 SonB 对象 b,并将其赋值给 FatherA 类型的变量 a。
代码1中使用 super 调用了父类的构造方法,初始化了父类的 x 和 y 字段。同时,子类也有自己的 x 和 y 字段。
代码2和代码3分别调用了子类和父类的 compare 方法。由于子类重写了父类的 compare 方法,因此代码2输出的是子类的 x+y 的结果,而代码3输出的是父类的 x+y 的结果。
代码4和代码5分别调用了子类和父类的静态方法 show。静态方法是不受对象影响的,因此无论是调用子类的静态方法还是父类的静态方法,输出的都是对应类中定义的静态方法的内容。因此,代码4输出的是 SonB 类的静态方法的内容,而代码5输出的是 FatherA 类的静态方法的内容。注意,子类的静态方法不能重写父类的静态方法,因此代码4中的 SonB 类的静态方法并没有覆盖 FatherA 类的静态方法。
相关问题
class FatherA{ int x,y; FatherA(int x,int y){this.x=x;this.y=y;} static void show(){ System.out.println("FatherA静态方法"); } void compare(){ System.out.println(x+y); } } class SonB extends FatherA{ int x,y; Son
B(int x,int y,int a,int b){ super(x,y); this.x=a; this.y=b; } static void show(){ System.out.println("SonB静态方法"); } void compare(){ super.compare(); System.out.println(x+y); } }
以上是一个Java代码,其中FatherA是父类,SonB是子类。
父类和子类都有x和y属性,但是子类中的x和y是新定义的,与父类中的x和y不同。
父类中有一个compare()方法,输出x和y的和,而子类中也有一个compare()方法,先调用父类的compare()方法,再输出子类中的x和y的和。
父类中有一个静态方法show(),输出"FatherA静态方法",而子类中也有一个静态方法show(),输出"SonB静态方法",这种情况下,当通过子类调用静态方法show()时,输出的是"SonB静态方法",而不是"FatherA静态方法"。
解释下面这段代码并输出值class FatherA{ int x,y; FatherA(int x,int y){this.x=x;this.y=y;} static void show(){ System.out.println("FatherA静态方法"); } void compare(){ System.out.println(x+y); } } class SonB extends FatherA{ int x,y; SonB(int x,int y) { super(x,y);//代码1 this.x=x; this.y=y; } void compare(){ System.out.println(x+y); } static void show(){ System.out.println("SonB类的静态方法"); } } public class Test { public static void main(String[] args) { FatherA a; SonB b=new SonB(10,20); a=b; b.compare();//代码2 a.compare();//代码3 b.show();//代码4 a.show();//代码5 } }
以上代码定义了一个父类FatherA和一个子类SonB,SonB是FatherA的子类。在Test类的main方法中,创建了一个SonB对象b,并将其赋值给FatherA类型的变量a。
在代码行1中,FatherA类有一个构造函数,用于初始化父类的成员变量x和y,使用this关键字来指代当前对象。
在代码行3中,FatherA类有一个静态方法show(),输出"FatherA静态方法"。
在代码行4中,FatherA类有一个实例方法compare(),输出x+y的值。
在代码行5中,SonB类继承了FatherA类,并且添加了自己的成员变量x和y。在SonB类的构造函数中,使用super关键字调用父类的构造函数,初始化父类的成员变量x和y,然后使用this关键字初始化子类的成员变量x和y。
在代码行8中,SonB类重写了compare()方法,输出子类自己的x+y的值。
在代码行9中,SonB类有一个静态方法show(),输出"SonB类的静态方法"。
在代码行12中,b.compare()输出30,因为子类的compare()方法被调用,输出子类自己的x+y的值。
在代码行13中,a.compare()输出30,因为a指向的是一个SonB对象,调用的是子类的compare()方法,输出子类自己的x+y的值。
在代码行14中,b.show()输出"SonB类的静态方法",因为调用的是子类的静态方法show()。
在代码行15中,a.show()输出"FatherA静态方法",因为静态方法不具有多态性,调用的仍然是父类的静态方法show()。