短实习---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();
}
}
- 短实习---Java面向对象(练习题)
- 短实习---Java面向对象(练习题)
- 短实习----Java面向对象(基础知识)
- 短实习---java数据类型(练习题)
- 短实习----Java数组(练习题)
- 短实习---Java接口、关键字(练习题)
- 短实习---Java多线程(练习题)
- java面向对象 练习题1
- java面向对象 练习题2
- java基础3--面向对象(上)(综合练习题)
- java基础4--面向对象下(几道练习题)
- java 第八天 面向对象(基础篇之练习题)
- java学习之路 之 面向对象编程-面向对象-数组练习题(1)
- 短实习---java数据类型(基础知识)
- 短实习---java数组(基础知识)
- 短实习---Java方法(基础知识)
- 短实习---Java接口、关键字(基础知识)
- 短实习---Java集合(基础知识)
- Lua语法小贴士(十六)pairs和next
- SQL数据库安装
- C++多态的概念以及用途
- ubuntu for AM5728
- android网络调试工具Stetho介绍
- 短实习---Java面向对象(练习题)
- 51nod 1289 大鱼吃小鱼
- 仿中国比特币首页趋势图,折线图,k线图
- HDU
- BZOJ 4540: [Hnoi2016]序列 莫队算法
- iOS支持富文本Label控件
- android 跑马灯出现重复跳动、不滚动问题
- Spring Boot --微信企业号开发01-使用新花生壳进行本地开发测试
- MacOS 开发- NSBox