短实习---Java面向对象(练习题)

来源:互联网 发布:咫尺网络微官网 编辑:程序博客网 时间:2024/05/16 14:20

1.定义一个点Point类,包含2个成员变量x,y分别表示x和y坐标,2个构造器Point()和Point(int x0,int y0),以及一个movePoint(int dx,int dy)方法实现点的位置移动,创建两个Point对象p1,p2,分别调用movePoint方法后,打印p1和p2的坐标。

public class Point{

int x;

int y;

//无参构造器

public Point(){  }

//有参构造器

public Point(int x,int y){

this.x=x;

this.y=y;

}

}

//movePoint方法

public void movePoint(int dx,int dy){

this.x+=x;

this.y+=y;

System.out.println("坐标为("+this.x+","+this.y+")");

}

}

//测试类

public class PointTest{

public static void main(String [] args){

//创建实例

Point p1=new Point(1,2);

Point p2=new Point(3,4);

p1.movePoint(p2.x,p2.y);

}

}

2.定义一个矩形类Rectangle。定义三个方法:getArea()求面积,getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长。有两个属性,长length,宽width。通过构造方法Rectangle(int width,int length)分别给两个属性赋值;创建一个Rectangle对象,并输出相关信息

public class Rectangle{

double length;

double width;

public Rectangle(int width,int length){

this.length=length;

this.width=width;

}

public double getArea(int length,int width){

return this.length*this.width;

}

public double getPer(int length,int width){

return 2*(this.length+this.width);

}

public void showAll(int length,int width){

System.out.println("长"+this.length+","+this.width);

System.out.println("面积是"+this.length*this.width);

System.out,println("周长是"+2*(this.length+this.width));

}

}

//测试类

public RectangleTest{

public static void main(String []args){

Rectangle r=new Rectangle(2,4);

r.showAll();

}

}

3.定义一个汽车类Vehicle,要求如下:属性包括:汽车品牌brend,颜色color和速度speed,并且所有属性为私有;至少提供一个有参的构造方法(要求品牌和颜色可以初始化为任意值,但速度的初始值必须为0);为私有属性提供访问器方法。注意,汽车品牌一旦被初始化后不能更改;定义一个一般方法run(),用打印语句描述汽车奔跑的功能;定义测试类VehicleTest,在其main方法中创建一个品牌“benz”、颜色为“black”的汽车;

public class Vehicle{

private String brend;

private String color;

private double speed=0.0;

public Vechicle(){ }

public Vechicle(String brend,String color,double speed){

this.brend=brend;

this.color=color;

this.speed=speed;

}

public void run(){

System.out.println(this.brend+"," +this.color+","+this.speed);

}

}

//测试类

public class VehicleTest{

public static void main(String [] args){

Vehicle v= new Vehicle("benz","black",23.9);

v.run();

}

}

原创粉丝点击