在下面的代码中添加一个名为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
本文介绍了如何在Java中创建一个名为A的类,该类继承自Person类,并添加了一个年龄字段。A类的构造函数接受年龄参数,并通过super关键字调用父类构造函数初始化。同时,A类重写了Person的pfun方法,输出包括id、name和age在内的三个字段。
3728

被折叠的 条评论
为什么被折叠?



