题目1:创建Person接口(即“人”),它有setData()和getData()方法对“人”属性name、sex和birthday赋值和获得这些属性组成的字符串信息。创建类Student实现Person接口,并对自己的“学生”属性的成员变量sID、speciality设置值和获得它们值所组成的字符串信息。
代码:
People.java(接口)
package com.interfaces;
public interface People {
public void setData(String name,String sex,String birthday);
public String getData();
}
Student.java(实现接口的类)
package com.interfaces.impl;
import com.interfaces.People;
public class Student implements People {
private String name;
private String sex;
private String birthday;
private String sID="2014";
private String speciality="写代码";
@Override
public void setData(String name, String sex, String birthday) {
// TODO Auto-generated method stub
this.name=name;
this.sex=sex;
this.birthday=birthday;
}
@Override
public String getData() {
// TODO Auto-generated method stub
return "名字: " + name + ",性別: " + sex + ",生日: " + birthday + ",ID: " + sID + ",专长: " +speciality;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
People Yantai=new Student();
Yantai.setData("海哥", "男", "2017年2月19日");
System.out.println(Yantai.getData());
}
}
题目2:
编写程序,求柱体的体积:
(1)、为柱体的底面设计一个接口Geometry,包含计算面积的方法getArea();
(2)、为柱体设计类pillar,要求:
a)有两个成员变量,底面和高度。底面是任何可以计算面积的几何形状。
b)实现构造方法,对成员变量赋值。
c)包含成员方法,计算柱体pillar的体积。
(3)、编写测试类圆形类、矩形类实现Geometry接口,编写测试类Test,分别用圆形、矩形作为柱体的底面,并计算其体积。
代码:
Geometry.java(接口)
package com.interfaces;
public interface Geometry {
public double getArea();
}
Test.java(接口实现类)
package com.interfaces.impl;
import com.interfaces.Geometry;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Pillar pillar;
Geometry bottom;
bottom = new Rect(10, 5); //接口实现方法
pillar = new Pillar(bottom, 5);
System.out.println("矩形底的柱体的体积:" + pillar.Volume());
bottom = new Circle(5);
pillar = new Pillar(bottom, 5);
System.out.println("圆形底的柱体的体积:" + pillar.Volume());
}
/*
* 柱体设计类
*/
class Pillar{
Geometry bottom;
double height;
public Pillar(Geometry bottom, double height){
this.bottom=bottom;
this.height=height;
}
public double Volume(){
return bottom.getArea()*this.height;
}
}
/*
* 矩形测试类
*/
class Circle implements Geometry{
double radius;
public Circle(double radius){
this.radius = radius;
}
public double getArea() {
// TODO Auto-generated method stub
return Math.PI*this.radius*this.radius;
}
}
/*
* 圆形测试类
*/
class Rect implements Geometry{
double wide,length;
public Rect(double wide, double length){
this.wide = wide;
this.length = length;
}
public double getArea() {
return wide*length;
}
}
}