在类的方法定义中使用this关键字代表使用该方法的对象的引用
this可以看作一个变量,它的值是当前对象的引用
1.定义一个“点”(Point)类用来表示三维空间中的点(有三个坐标)。要求如下:
a) 可以生成具有特定坐标的点对象
b) 提供可以设置三个坐标的方法
c) 提供可以计算该“点”距离原点距离平方的方法
d) 编写程序验证上述三条(通过main方法)
public class Point {
double x,y,z;
public Point(){
x=0;
y=0;
z=0;
}
public Point(int x,int y,int z){
this.x=x;
this.y=y;
this.z=z;
}
public double distance(){
return x*x+y*y+z*z;
}
public static void main(String[] args) {
Point a=new Point(1,2,3);
System.out.println(a.distance());
}
}

- 创建一个新的日期(Date)类
a) 其中应该包含3个整型成员变量,分别为year、month和day。
b) 为Date类创建两个构造函数,其中一个不带参数,另一个接受3个参数,分别为year、month和day,在构造函数中为相应的实例成员变量进行初始化。
c) 提供一个打印日期的方法。
d) 编写一个main方法,在该方法中创建一个名为birthday的Date对象,用该Date对象来表示你自己的生日,并打印。
public class Date {
int year,month,day;
public Date(){
}
public Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public String ad(){
return year+"-"+month+"-"+day;
}
public static void main(String[] args) {
Date birthday=new Date(2000,2,15);
System.out.println(birthday.ad());
}
}

定义一个描述部门的简单Java类Deptment,如下表所示:

要求:
根据表创建对应的成员变量。
为Department类创建两个构造函数,其中一个不带参数,另一个接受3个参数,形参要求名称和成员变量名称相同,在构造函数中为相应的实例成员变量进行初始化,初始化数据如上表所示。
提供一个打印部门信息的方法。
编写一个main方法,在该方法根据上表所示创建两个对象,并打印。
public class Deptment {
int deptno;
String dname;
String dloc;
public Deptment(){
deptno=10;
dname="研发中心";
dloc="杭州";
}
public Deptment(int deptno,String dname,String dloc){
this.deptno=deptno;
this.dname=dname;
this.dloc=dloc;
}
public String af(){
return deptno+" "+dname+" "+dloc;
}
public static void main(String[] args) {
Deptment ac=new Deptment();
Deptment ab=new Deptment(11,"销售部","北京");
System.out.println(ac.af());
System.out.println(ab.af());
}
}


public class Leaf {
int i;
public Leaf(int i){
this.i=i;
}
Leaf increament(){
i++;
return this;
}
void print(){
System.out.println("i=" + i);
}
public static void main(String[] args) {
Leaf leaf=new Leaf(100);
leaf.increament().increament().print();
}
}

网友评论