面向對象設計思想
1.考慮問題涉及哪些個類和對象;
2.分析類和對象所需要具有的屬性和方法;
3.類和類之間具備了怎樣的關係;
成員變量若未初始化,系統會默認爲其初始化;而局部變量未對其初始化則無法使用;
引用:相當於指針(一小塊內存指向一大塊內存)
對象是通過引用new出來的,存在堆內存裏;
new出來的對象中是該對象獨有的屬性;
構造方法
public class Person {
int id;
int age =20;
//構造方法(和類同名,沒有返回值)
//構建對象的模板
Person(int _id,int _age){
id = _id;
age = _age;
}
/*常見錯誤:前面不能加任何返回值,加返回值變爲普通方法
* void Person(int _id,int _age){
id = _id;
age = _age;
}
*/
//new + 構造方法==創建對象
//調用構造方法來創建對象,_id,_age在棧內存中賦值,
//傳遞給創建的對象,完成對新建對象的創建,之後回收構造方法調用後的“垃圾”;
public static void main(String[] args){
Person Tom = new Person(1,25);
//若已經指定某種形式的構造方法,系統不會添加默認形式的構造方法,
//也就無法調用,
//例如下面的調用形式無法執行
/*Person jerry = new Person();
jerry.id = 1;
jerry.age = 22;
*/
Point p = new Point();
//p.x==p.y==0 系統默認值爲0
//System.out.print(p.x);
//System.out.println(p.y);
}
}
class Point{
int x;
int y;
Point(){}//系統自動設定的構造方法
}
約定俗成的命名規則:
1.類名首字母大寫;
2.方法名,參數名首字母小寫;
3.運用駝峯標識
class BirthDate {
int day;
int month;
int year;
public BirthDate(int _d,int _m,int _y){
day = _d;
month = _m;
year = _y;
}
public void setDay(int _d){
day = _d;
}
public void setMonth(int _m){
month = _m;
}
public void setYear(int _y){
year = _y;
}
public int getDay(int _d){
return _d;
}
public int getMonth(int _m){
return _m;
}
public int getYear(int _y){
return _y;
}
}
public class Test {
public void change1(int i){
i = 1234;
}//i值改爲1234後被回收,over
public void change2(BirthDate d){
d = new BirthDate(2,3,2020);
//test.change2(d2); d2調用時,d先指向d2對象,
//再創建一個新的對象,但方法結束後被回收,不會改變d2中值
}
public void change3(BirthDate d){
d.setDay(22);//在當前對象引用下真正的改變了值
}
public static void main(String[] args){
Test test = new Test();
int date = 9;
BirthDate d1 = new BirthDate(7,7,1970);
BirthDate d2 = new BirthDate(1,1,2000);
test.change1(date);
test.change2(d2);
test.change3(d2);
System.out.println("d1:"+d1.day+"-"+d1.month+"-"+d1.year);
System.out.println("d2:"+d2.day+"-"+d2.month+"-"+d2.year);
}
}
//d1:7-7-1970
//d2:22-1-2000
class Points{
double x;
double y;
double z;
//構造方法
public Points( double _x,double _y,double _z){
x = _x;
y = _y;
z = _z;
}
//set方法
public void setX(double _x){
x = _x;
}
public void setY(double _y){
y = _y;
}
public void setZ(double _z){
z = _z;
}
public double getDistance(Points 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){
Points p1 = new Points(1.0,2.0,3.0);
Points p2 = new Points(1.0,-3.0,3.0);
double d = p1.getDistance(p2);
System.out.println(d);
p1.setX(3.0);
System.out.println(p1.getDistance(p2));
}
}