在下面的代码中添加一个名为A的类。
A类是Person的子类。 在A中定义一个字段(年龄),
构造函数和重写Person的pfun方法的方法,
*在方法中使用超级关键字,输出三个字段。
Add a class, named A to the following codes. Class A is a sub class of Person. In A, define a field (age), a constructor and a method which overrides the pfun method of Person, use super keyword in the method, output the three fields…
public class Person {
private int id;
private String name;
void pfun(){
System.out.println(“id=”+id);
System.out.println(“name=”+name);
}
Person(int a, String b) {
id=a;
name=b;
}
public static void main(String[] args) {
A k=new A(102,“Wang”,22);
k.pfun();
}
}
public class Person {
private int id;
private String name;
void pfun(){
System.out.println("id="+id);
System.out.println("name=" +name);
}
Person(int a, String b) {
id=a;
name=b;
}
public static void main(String[] args) {
A k=new A(102,"Wang",22);
k.pfun();
}
}
class A extends Person{
int age;
A(int a, String b,int age) {
super(a, b);
this.age=age;
}
void pfun() {
super.pfun();
System.out.println("age:"+a);
}
}
运行结果:
id=102
name=Wang
age:22