继承性的练习
一
代码一
package eightdemo;
/**
* 1.(1)定义一个ManKind类,包括
* 成员变量int sex和int salary;
* 方法void manOrWorman():根据sex的值显示“man”(sex==1)或者“women”(sex==0);
* 方法void employeed():根据salary的值显示“no job”(salary==0)或者“ job”(salary!=0)。
*/
public class ManKind {
private int sex;
private int salary;
public int getSex(){
return sex;
}
public void setSex(int sex){
this.sex = sex;
}
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary = salary;
}
public void manOrWomen(){
if(sex == 1)
System.out.println("Man");
else if(sex == 0)
System.out.println("Woman");
else
System.out.println("输入的数据有误");
}
public void employees(){
if(salary == 0)
System.out.println("no job");
else if(salary > 0)
System.out.println("job");
}
}
代码二
package eightdemo;
/**
* (2)定义类Kids继承ManKind,并包括
* 成员变量int yearsOld;
* 方法printAge()打印yearsOld的值。
*/
public class Kids extends ManKind {
private int yearsOld;
public int getYearsOld() {
return yearsOld;
}
public void setYearsOld(int yearsOld) {
this.yearsOld = yearsOld;
}
public void printAge() {
System.out.println(this.yearsOld + "years old");
}
public void employees() {
System.out.println("Kids should study and no job");
}
}
代码三
package eightdemo;
/**
* (3)在Kids类的main方法中实例化Kids的对象someKid,用该对象访问其父类的成员变量及方法。
*/
public class TestKids {
public static void main(String[] args) {
Kids someKid = new Kids();
someKid.setSalary(0);
someKid.setSex(1);
someKid.setYearsOld(13);
someKid.employees();
someKid.manOrWomen();
someKid.printAge();
}
}
二
代码一
package eightdemo;
public class Circle {
private double radius;
public Circle(){
this.radius = 1;
}
public double getRadius(){
return radius;
}
public void setRadius(double radius){
this.radius = radius;
}
//计算园的面积
public double findArea(){
return Math.PI * radius * radius;
}
}
代码二
package eightdemo;
public class Cylinder extends Circle {
private double length;//圆柱的高
public Cylinder(){
length = 1;
}
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
//重写父类Circle 的方法,求圆柱的表面积
public double findArea(){
// return 3.14 * this.getRadius() * this.getRadius() * 2 + 2 * 3.14 * this.getRadius() * this.getLength();
return super.findArea() * 2 + 2 * 3.14 * this.getRadius() * this.length;
}
//圆柱的体积
public double findVolume(){
// return Math.PI * this.getRadius() * this.getRadius() * length;
return super.findArea() * length;
}
}
代码三
package eightdemo;
/**
* 在TestCylinder类中创建Cylinder类的对象,设置圆柱的底面半径和高,并输出圆柱的体积。
*/
public class TestCylinder {
public static void main(String[] args) {
Cylinder c = new Cylinder();
double area = c.findVolume();
System.out.println(area);
c.setRadius(2.3);
c.setLength(1.2);
area = c.findVolume();
System.out.println(area);
c.findArea();
}
}
韧桂 2019-12-25