一、成员变量默认会初始化,局部变量不会自动初始化。
二、练习:
定义一个“点”(Point)类来表示三维空间中的点(有三个坐标)。要求如下:
1,可以生成具有特定坐标的点对象。
2,提供可以设置三个坐标的方法
3,提供可以计算该点距原点距离平方的方法
4,编写程序验证上述三条。
解: 自己的做法(模仿上一个例子):
class Point{
private int length;
private int width;
private int high;
public Point(int x,int y,int z){
length = x;
width = y;
high = z;
}
void setX(int x){
length = x;
}
void setY(int y){
width = y;
}
void setZ(int z){
high = z;
}
int distance(int x,int y,int z){
int result = 0;
result = x*x + y*y +z*z;
return result;
}
public void display(){
System.out.println("length = " + length + "width = " + width + "high = " + high);
}
}
public class TestPoint {
public static void main(String args[]){
TestPoint testpoint = new TestPoint();
int h = 10;
Point p1 = new Point(7,8,9);
Point p2 = new Point(1,4,6);
testpoint.change1(h);
testpoint.change2(p1);
testpoint.change3(p2);
System.out.println("h = " + h);
p1.display();
p2.display();
}
public void change1(int z){
z = 5;
}
public void change2(Point p){
p = new Point(7,5,6);
}
public void change3(Point p){
p.setX(22);
}
}
结果如下:
老师的答案:
class Point {
double x, y, z;
Point(double _x, double _y, double _z) {
x = _x;
y = _y;
z = _z;
}
void setX(double _x) {
x = _x;
}
double getDistance(Point p) {
return (x - p.x)*(x - p.x) + (y - p.y)*(y - p.y) + (z - p.z)*(z - p.z);
}
}
public class TestPoint {
public static void main(String[] args) {
Point p = new Point(1.0, 2.0, 3.0);
Point p1 = new Point(0.0, 0.0, 0.0);
System.out.println(p.getDistance(p1));
p.setX(5.0);
System.out.println(p.getDistance(new Point(1.0, 1.0, 1.0)));
}
}
分析:老师的做法更加精简而且适应性更强。不仅可以计算指定点到原点的距离,扩大到可以算两点之间的距离。
通过这次联系,对于类的建立。以及public class 的建立又有了新的一点点理解。任务很紧凑,架构平台老师还要求一个月内完成纯jsp/servlet的网上宠物商店,自己的进度需要加快!加油!!!!!!
三、方法的重载(overload)是指一个类中可以定义多个名字相同参数不同的方法。
四、非静态方法是针对每个对象进行调用。