练习:用类实现抽象数据类型(构造函数初始化)(继承)(方法重写)(创建类的对象)

10 篇文章 0 订阅
9 篇文章 0 订阅

本文为博主原创文章,未经博主允许不得转载。

编程,该程序包括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();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值