比如有各種各樣的汽車,有轎車、貨車、面包車等,這些機動車輛都可以被認為是對象,如果讓我們用一個詞去概括它們(就是抽象的過程)那是什么呢?是汽車,它們都可以被稱為汽車(所以說,類是對象的抽象)。汽車這個概念是我們跟據不同的汽車抽象出來的,它能包括馬路上所有的機動車輛,那么汽車這個概念就可以針對我們java中的類,它并不是具體指哪一輛汽車,也不是具體指那一種汽車,它是一個統稱(模板)它具有一定的內容(屬性的集合),比如說,必須動力驅動、有車輪等屬性,如果想讓一個對象被稱為是汽車,你必須滿足這些屬性(類是模板),如果是馬拉的車,那就不能叫汽車了。這就是Java中類概念的內涵。
現在我們已經抽象出一個類——汽車類,汽車有不同的牌子,有不同的顏色,不同的形狀,我們稱每一輛具體的汽車為汽車類的一個實例,從汽車類到具體汽車的過程被稱為實例化的過程,又稱為類(汽車類)的實例化。在Java中一個類的實例化是通過關鍵字“new”來進行的。
比如說我們現在聲明一個汽車類:
public class Car
{
……
}
進著進行一個類的實例化:
new Car();
一個類的實例是針對一個具體的對象的,它是一些具體屬性的集合,
設計自己的類
下面設計一個自己的類,我們的目的是做一個小型的學生管理系統,既然是學生管理系統,我們必須要擁有學生類,下面我們就開始設計一個學生類。
需求分析:
1、 對于一個學生類(class Student),作為整個系統最核心的類,我們希望它能包括學生公有的基本信息:學生姓名、學號、性別、出生年月、專業、籍貫等。
2、 做為學生類的實例,我們希望能通過設置或訪問來修改這些學生的不同信息。
public class StudentTest
{
public static void main(String[] args)
{
Student tom=new Student("Tom","20020410");
tom.setStudentSex("man");
tom.setStudentAddress("
System.out.println(tom.toString());
}
}
class Student
{
private String strName=""; //學生姓名
private String strNumber=""; //學號
private String strSex=""; //性別
private String strBirthday=""; //出生年月
private String strSpeciality=""; //專業
private String strAddress="";
public Student(String name,String number)
{
strName=name;
strNumber=number;
}
public String getStudentName()
{
return strName;
}
public String getStudentNumber()
{
return strNumber;
}
public void setStudentSex(String sex)
{
strSex=sex;
}
public String getStudentSex()
{
return strSex;
}
public String getStudentBirthday()
{
return strBirthday;
}
public void setStudentBirthday(String birthday)
{
strBirthday=birthday;
}
public String getStudentSpeciality()
{
return strSpeciality;
}
public void setStudentSpeciality(String speciality)
{
strSpeciality=speciality;
}
public String getStudentAddress()
{
return strAddress;
}
public void setStudentAddress(String address)
{
strAddress=address;
}
public String toString()
{
String information="學生姓名="+strName+",學號="+strNumber;
if(!strSex.equals(""))
information+=",性別="+strSex;
if(!strBirthday.equals(""))
information+=",出生年月="+strBirthday;
if(!strSpeciality.equals(""))
information+=",專業="+strSpeciality;
if(!strAddress.equals(""))
information+=",籍貫="+strAddress;
return information;
}
}
分析:
在程序中我們構建了一個學生類的實例:
Student tom=new Student("Tom","20020410");
這樣的過程就是類的實例化的過程。tom是Student類實例的句柄,也就是我們所說的對象句柄,在后面對對象所進行的任何操作,都是通過操作對象句柄進行的。我們通過關鍵字new生成Student類的一個實例,一個實例代表的是一個特定屬性的對象,我們生成的特定對象是學生:姓名是tom,學號是20020410的一個學生。
構造器(構造方法)
能過關鍵字new來生成對象的實例,是通過構造器(constructor)來實現的。簡單的說:構造器是同類名相同的特殊方法。
public Student(Student name,String number)
{
strName=name;
strNumber=number;
}
當構造一個學生類的實例時,學生類的構造器就被啟動,它給實例字段賦值。
構造器與方法的不同之處是:構造器只能與關鍵字new一起使用,構建新的對象。構造器不能應用于一個已經存在的對象來重新設置實例字段的值。
構造器的特點:
1、 構造器與類名相同(包括大小寫)
2、 一個類可有多個構造器。
3、 構造器可以有0個、1個或多個參數。
4、 構造器沒的返回值,但不能用void修飾。
構造器總是和new運算符一起被調用。