java中的构造方法


直接上题型:

建立一个三维空间,设定一个点

要求:

①可以生成具有特定坐标的点对象
②此点可以任意设置

③求此点到原点的距离平方

题目解析:

可以生成特定坐标,并可以设置,由此可知需要“”构造方法”,以及setX,setY,setZ等普通方法

为什么可以“构造方法”,首先要理解构造方法的作用-----变量初始化。

知道了构造方法的作用,就可以生成特定坐标,并给他赋一个初始值,这样方便之后对其内容的更改。

代码:

package com.company;

import java.io.PipedInputStream;

class Point{
//设置未知量
int x;
int y;
int z;
//构造方法
Point(int _x,int _y,int _z){
x=_x;
y = _y;
z= _z;
}

public void setX(int x) {
this.x = x;
}

public void setY(int y) {
this.y = y;
}

public void setZ(int z) {
this.z = z;
}

public int getX() {
return x;
}

public int getY() {
return y;
}

public int getZ() {
return z;
}

int Display(Point p){
return (x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)+(z-p.z)*(z-p.z);
}
}
public class Main {

public static void main(String[] args) {
Main test = new Main();
Point p = new Point(1,2,3);
Point p1 = new Point(0,0,0);
// test.chengji(p);
System.out.println( p.Display(p1));
test.changeX(p);
System.out.println(p.Display(new Point(1,1,1)));
}
void changeX(Point x){
x.setX(5);
}
void changeY(Point y){
y.setY(3);
}
void changeZ(Point Z){
Z.setZ(5);
}
}