本文为博主原创文章,未经博主允许不得转载。
编程,该程序包括3个类:Person类,Children类和主类E。要求:
(1)创建一个Person类,成员变量有姓名(Name,String类型)、年龄(age,整形);包含带参数构造方法对姓名和年龄进行初始化;有public void work()方法,在work()方法中输出"Person love working"的信息。
(2)创建Person的子类Children,工作行为不同,重写work方法,显示"Children like playing games."。
(3)在Children中新增方法eat(),在eat方法中输出"Chocolate is so delious!"的信息。
(4)在主类E的main方法中创建Person和Children类的对象,测试这两个类的功能。
class Person
{
String Name;
int age;
public Person(String name,int age1)
//隐式构造 构造函数(带参数)
{
Name=name;
age=age1;
}
public Person()
//显示构造 构造函数
//必须定义显示构造函数,这样才算构造函数Person()被定义,才能被继承,
//否则Children会报错
{
}
public void work()
{
System.out.println("名字:"+Name);
System.out.println("年龄:"+age);
System.out.println("Person love working.\n");
}
}
public class Children extends Person
{
public void work()
{
System.out.println("Children like playing games.");
}
public void eat()
{
System.out.println("Chocolate is so delicious!");
}
}
public class E
{
public static void main(String[] args)
{
Person boy1=new Person("张哲瀚",18);
//初始化信息
boy1.work();
Children boy2=new Children();
boy2.work();
boy2.eat();
}
}
下面代码是直接初始化
class Person
{
String Name="张哲瀚";
int age=18;
//直接初始化
public void work()
{
System.out.println("名字:"+Name);
System.out.println("年龄:"+age);
System.out.println("Person love working.\n");
}
}
public class Children extends Person
{
public void work()
{
System.out.println("Children like playing games.");
}
public void eat()
{
System.out.println("Chocolate is so delicious!");
}
}
public class E
{
public static void main(String[] args)
{
//Person boy1=new Person();
Person boy1=new Person();
boy1.work();
Children boy2=new Children();
boy2.work();
boy2.eat();
}
}