類與對象
對象:
對象表示現實世界中某個具體的事物
抽象是從特定大的執行個體中抽取共同的性質以形成一般化概念的過程。
對象具有兩方面的含義:
在現實世界中:
是客觀世界中的一個實體
在計算機世界中:
是一個可辨別的存儲區域(後面做詳細解釋)
類(class)
類是具有共同屬性和行為的對象的抽象
類的定義
java類的基本文法:
<修飾符> class <類名>{
[<屬性聲明>]
[<構造器聲明>]
[<方法聲明>]
}
person類的成員變量的定義
class person{
private string name = null;
private int age = 0;
private double height = 0;
private double weight = 0;
…
聲明方法
方法的基本文法:
<修飾符> <傳回類型> <名稱>([<參數表>]){
[<語句>]
}
person類的方法的定義
ublic double bmivalue(){
return weight/(height*height);
public double stdweight(){
return 22*height*height;
public double obesitydegree(){
return (weight-stdweight())/stdweight()*100;
public string conclusion(){
if(obesitydegree()<-10)
return "瘦";
else
if(obesitydegree()<20){
if(bmivalue()<24.2)
return "普通";
else
return "超重";
}
else
return "肥胖";
person類的構造函數的定義
public person( weight){
this.name=name;
this.age=age;
this.height=height;
this.weight=weight;
構造函數
構造函數的基本文法:
<修飾符> <類名>([<參數表>]){
[<語句>]
構造函數特點
構造函數作用:完成類對象的初始化工作
構造函數的名稱必須與類名相同
構造器沒有傳回值并且不可被繼承
一般将構造函數的修飾符聲明為public
構造函數中不能有return語句
構造函數參數
參數表與方法聲明中的一樣。可以像方法一樣向構造函數傳遞參數。
構造函數可以有0個、1個或者多個參數。
無參數的構造函數
沒有構造函數——使用預設的構造函數(沒有參數,沒有方法體)
如果使用沒有參數的構造函數,則建立的對象具有相同的初始值
修改補充例1
private string name = "model";
private int age=20;
private double height = 1.7;
private double weight = 60;
public person(){}
繼續修改補充例1
public person(){
this.name="jack";
this.age=30;
this.height=1.8;
this.weight=80;
帶參數的構造函數
public person(string name,int age,double height,double weight){
構造函數的重載
一個類可以有多個構造函數,叫做構造函數的重載。
條件(滿足其一)
參數的個數不同
參數的類型不同
構造函數的使用
不能由程式設計人員顯式調用。
在建立一個類的新對象的同時,系統會自動調用該類的構造函數為新對象初始化。
構造函數隻能和new關鍵字一起使用。
格式
類名 對象名
=new 構造函數名稱(成員變量的初始值)
public person(string name,int age,double height,double weight){
public person(string name,int age){
this.height=1.7;
this.weight=70;
}
public person(string name){
this.age=25;
this.height=1.5;
this.weight=50;
構造函數的互相調用
public person(string name,int age,double height,double weight){
public person(string name,int age){
this(name,age,1.7,70);
this(name,25,1.5,50);
預設構造函數
每個類至少有一個構造函數。
如果不編寫構造函數,則自動添加預設構造函數:
預設構造函數不帶參數
預設構造函數函數體為空
不必編寫構造函數就能使用new xxx()建立
對象執行個體
注意:當編寫了構造函數以後,預設的構造函數就會消失
找錯誤?
} }
class test{
public static void main(string[] args){
person p1=new person();
person p2=new person(“jerry”,20,1.9,100);
以上哪個語句有錯?
為什麼?
對象(類的執行個體化)
class samecircle{
public int norignx;
public int norigny;
public int nradius;
public samecircle(int norignx,int norigny,int nradius){
this.norignx=norignx;
this.norigny=norigny;
this.nradius=nradius;
}
對象的生成 (1)對象的聲明
格式:<類名> <對象名>;
如:samecircle c1,c2;
c1和c2是兩個空對象。
建立對象
格式:<對象名>=new <類名>(實參);
如:c1=new samecircle(3,4,5);
c2=new samecircle(6,7,8);
對象的引用
samecircle c1=new samecircle(3,4,5);
samecircle c2=c1;
對象的清除
對象為null時,由java的自動垃圾收集機制清除對象,釋放對象占用記憶體
手動編寫finalize()方法撤銷對象——不提倡使用
注意二者的差別
棧stack——連續的記憶體區域,大小固定,編譯時确定所需空間大小,效率高
堆heap——不連續的記憶體區域,運作時确定所需空間大小(支援面向對象的多态性,如:運作時才能确定是哪個類的對象),效率低,但靈活
補充知識:對象的記憶體模型
棧記憶體:在方法中定義的變量(基本類型和引用類型)。超過變量的作用域時,自動釋放變量的記憶體
堆記憶體:new建立的對象(包括數組),由java的自動垃圾收集機制來清除