5-1面向对象编程(中)----面向对象特征之二: 继承性练习1--Kids

本文介绍了如何定义ManKind类,包含性别和薪水属性,以及显示相应称呼和就业状态的方法。接着,扩展了Kids类,增加年龄属性并实现年龄打印。在KidsTest类的main方法中,实例化并演示了父类和子类的交互。输出结果展示了继承和方法调用的实际应用。
摘要由CSDN通过智能技术生成

(1)定义一个ManKind类,包括
①成员变量int sex和int salary;
②方法void manOrWoman():根据sex的值显示“man”(sex == 1)或者“woman”(sex == 0);
③方法void employeed():根据salary的值显示“no job”(salary==0)或者“ job”(salary!=0)。
(2)定义类Kids继承ManKind,并包括
①成员变量int yearsOld;
②方法printAge()打印yearsOld的值。
(3)定义类KidsTest,在类的main方法中实例化Kids的对象someKid,用该对象访问
其父类的成员变量及方法。

ManKind类:

public class ManKind {
 int sex;
 int salary;
 public ManKind() {
 }
 public ManKind(int sex, int salary) {
  this.sex = sex;
  this.salary = salary;
 }
 public void manOrWoman() {
  if (sex == 1) {
   System.out.println("man");
  } else if (sex == 0) {
   System.out.println("woman");
  }
 }
 public void employeed() {
//  if(salary == 0) {
//   System.out.println("no job");
//  }else if(sex == 0) {
//   System.out.println("job");
//  }
  String jobInfo = (salary == 0) ? "no job" : "job";
  System.out.println(jobInfo);
 }
}

Kids类:

public class Kids extends ManKind{
 int yearsOld;
 public Kids() {
 }
 public Kids(int yearsOld) {
  this.yearsOld = yearsOld;
 }
 public void printAge() {
  System.out.println("I am " + yearsOld + " years old.");
 }
}

KidsTest:

public class KidsTest {
 public static void main(String[] args) {
  Kids someKid = new Kids(12);

 someKid.printAge();

someKid.salary = 0;
  someKid.sex = 1;
  someKid.manOrWoman();
  someKid.employeed();
 }
}

输出:

I am 12 years old.
man
no job
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YY鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值