一个类MyAnimal,该类有三个属性:name、sex、age和方法:eat()、sleep()和属性的数据访问get、set方法。类Cat继承了MyAnimal。
文件名:Animal
package qi;
class MyAnimal{
String name;
String sex;
int age;
String eat() {
return"每天吃了。。。";
}
String seelp() {
return"每天睡。。小时";
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
String getSex() {
return sex;
}
void setSex(String sex) {
this.sex = sex;
}
int getAge() {
return age;
}
void setAge(int age) {
this.age = age;
}
}
class Cat extends MyAnimal{
}
public class Animal {
public static void main(String [] args){
Cat cat=new Cat();
cat.setName("猫");
cat.setAge(2);
System.out.println(cat.eat());
System.out.println("物种:"+cat.getName());
System.out.println("年龄"+cat.getAge());
}
}
编写一个圆类Circle,该类拥有:
①一个成员变量:Radius(私有,浮点型);//存放圆的半径
②两个构造方法:Circle() //将半径设为0
Circle(double r) //创建Circle对象时将半径初始化为r
③三个成员方法:Double getArea()//获取圆的面积
Double getPerimeter()//获取圆的周长
void show()//将圆的半径、周长、面积输出到屏幕
(2)编写一个圆柱体类Cylinder,它继承于上面的Circle类。还拥有:
①一个成员变量:double hight(私有,浮点型);//圆柱体的高;
②构造方法:Cylinder (double r, double h) //创建Circle对象半径初始化为r
③成员方法:double getVolume()//获取圆柱体的体积
void showVolume()//将圆柱体的体积输出到屏幕
编写应用程序,创建类的对象,分别设置圆的半径、圆柱体的高,计算并分别显示圆半径、圆面积、圆周长,圆柱体的体积。
文件名:Yuan
package qi;
class Circle{
private double Radius;
Circle(){
Radius=0;
}
Circle(double r){
Radius=r;
}
double getRadius() {
return Radius;
}
void setRadius(double radius) {
Radius = radius;
}
Double getArea() {
return 3.14*Radius*Radius;
}
Double getPerimeter() {
return 2*3.14*Radius;
}
void show() {
System.out.println("圆的半径为:"+Radius);
System.out.println("圆的面积为:"+getArea());
System.out.println("圆的周长为:"+getPerimeter());
}
}
class Cylinder extends Circle{
private double height;
Cylinder(double r,double h){
setRadius(r);
height=h;
}
double getVolume() {
return getArea()*height;
}
void showVolume() {
System.out.print("圆柱的体积为:"+getVolume());
}
}
public class Yuan {
public static void main(String[] args) {
Cylinder y=new Cylinder(1.8,3);
y.show();
y.showVolume();
}
}
编写一个Java应用程序,该程序中有1个Cat类继承Object类,具有三个成员属性String name、int furColor、int height,一个构造方法Cat(String name, int furColor, int height, int weight),并且重写Cat类的toString()和equals(Object obj)成员方法。具体要求如下:
(1)重写toString成员方法,返回值是成员属性String name的值。
(2)重写equals成员方法,如果两个Cat对象的furColor和height属性相等那么返回值是true,否则返回值是false。
文件名:ABC
package qi;
class Cat extends java.lang.Object{
String name;
int furColor;
int height;
Cat(String name, int furColor, int height, int weight){
this.name=name;
this.furColor=furColor;
this.height=height;
}
public String toString(){
return this.name;
}
public boolean equals(Object obj){
if(furColor==height)
return true;
else
return false;
}
}
public class ABC {
public static void main(String[] args) {
Cat a=new Cat("Cat",5,5,4);
System.out.println(a.toString());
System.out.print(a.equals(a));
}
}