在本節(jié)教程中,我們將學(xué)習(xí)Java對象和類。在面向?qū)ο缶幊碳夹g(shù)中,需要設(shè)計和使用對象和類的程序。對象是物理和邏輯實體,而類是邏輯實體。
提醒:對于Java初學(xué)者來說,對象和類是一個十分重要的概念,能否理解和掌握對之后其他Java知識有直接影響。所以,雖然本節(jié)的內(nèi)容比較多,但建議認真閱讀并理解,最好能結(jié)合手動實現(xiàn)本節(jié)中的所有示例代碼。
具有狀態(tài)和行為的實體可稱為對象(女朋友也可以叫對象)。 椅子,自行車,標(biāo)記,筆,桌子,汽車等。它可以是物理或邏輯(有形和無形)。 無形對象的例子是銀行系統(tǒng)。
一個對象有三個特點:
ID的值對外部用戶不可見。 但是,它由JVM內(nèi)部使用來唯一地標(biāo)識每個對象。例如: 汽車是一個對象。它的名字是:捷達,顏色是白色等這些就是它的狀態(tài)(數(shù)據(jù)值)。它用于跑路,所以跑路就是它的行為。
對象是類的一個實例。 類是創(chuàng)建對象的模板或藍圖。 所以對象是一個類的實例。
對象定義:
類是具有共同屬性的一組對象。它是創(chuàng)建對象的模板或藍圖。它是一個邏輯實體。 它不能是物理存在的實體。
Java中的類可以包含:
聲明一個類的語法:
class <class_name>{
field;
method;
}
實例變量在類內(nèi)部,但在方法外部定義的變量稱為實例變量。 實例變量在編譯時不獲取內(nèi)存。 它在運行時獲取對象(實例)創(chuàng)建時的內(nèi)存。 這是為什么,它被稱為實例變量。
在java中的方法類似函數(shù),用于暴露對象的行為。
方法的優(yōu)點
new關(guān)鍵字用于在運行時分配內(nèi)存。所有對象在堆內(nèi)存區(qū)域中獲取內(nèi)存。
在這個例子中,我們創(chuàng)建了一個有兩個數(shù)據(jù)成員:id和name的Student類。并通過使用new關(guān)鍵字創(chuàng)建Student類的對象,并打印對象的值。
這里,在類中創(chuàng)建main()方法。Student.java 類文件的代碼如下 -
class Student {
int id;// field or data member or instance variable
String name;
public static void main(String args[]) {
Student s1 = new Student();// creating an object of Student
System.out.println(s1.id);// accessing member through reference variable
System.out.println(s1.name);
}
}
上面代碼執(zhí)行結(jié)果如下 -
0
null
在真實的開發(fā)中,我們一般創(chuàng)建類并從另一個類中使用它。這是比上面的在同一個類中更好的方法。 讓我們來看一個簡單的例子,在另一個類中有main()方法創(chuàng)建其它類。
在不同的java文件或單個java文件中有多個類。 如果在單個java源文件中定義多個類,則最好使用帶有main()方法的類名作為保存的文件名。下面來看一個名稱為 TestStudent1.java 的文件中的代碼:
class Student {
int id;
String name;
}
class TestStudent1 {
public static void main(String args[]) {
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
執(zhí)行上面代碼,得到以下結(jié)果 -
0
null
在java中初始化對象有3種方式,它們分別如下 -
初始化對象僅僅是將數(shù)據(jù)初步地存儲到對象中。下面來看看一個簡單的例子,通過引用變量初始化對象。這里創(chuàng)建一個 TestStudent2.java 類文件,代碼如下:
class Student {
int id;
String name;
}
class TestStudent2 {
public static void main(String args[]) {
Student s1 = new Student();
s1.id = 101;
s1.name = "Sonoo";
System.out.println(s1.id + " " + s1.name);// printing members with a
// white space
}
}
上面代碼輸出結(jié)果如下 -
101 Sonoo
還可以通過引用變量創(chuàng)建多個對象并存儲信息在這些對象。這里創(chuàng)建一個 TestStudent3.java 類文件,代碼如下:
class Student {
int id;
String name;
}
class TestStudent3 {
public static void main(String args[]) {
// Creating objects
Student s1 = new Student();
Student s2 = new Student();
// Initializing objects
s1.id = 101;
s1.name = "Sonoo";
s2.id = 102;
s2.name = "Amit";
// Printing data
System.out.println(s1.id + " " + s1.name);
System.out.println(s2.id + " " + s2.name);
}
}
上面代碼輸出結(jié)果如下 -
101 Sonoo
102 Amit
在本示例中,將創(chuàng)建Student類的兩個對象,并通過調(diào)用insertRecord方法來初始化這些對象的值。并通過調(diào)用displayInformation()方法顯示對象的狀態(tài)(數(shù)據(jù))。這里創(chuàng)建一個 TestStudent4.java 類文件,代碼如下:
class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " " + name);
}
}
class TestStudent4 {
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111, "Karan");
s2.insertRecord(222, "Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
執(zhí)行上面代碼,得到如下結(jié)果 -
111 Karan
222 Aryan
創(chuàng)建對象的示意如下 -

從上圖可以看出,對象在堆內(nèi)存區(qū)域獲取內(nèi)存。 引用變量指的是在堆內(nèi)存區(qū)域中分配的對象。 這里,s1和s2都是引用存儲器中分配的對象的引用變量。
有關(guān)于通過構(gòu)造函數(shù)初始化對象,我們將在后面的Java構(gòu)造函數(shù)中學(xué)習(xí)。
下面我們來看看一個例子,實現(xiàn)維護員工信息的記錄。這里創(chuàng)建一個 TestEmployee.java 類文件,代碼如下所示 -
class Employee {
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id = i;
name = n;
salary = s;
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
e1.insert(101, "ajeet", 45000);
e2.insert(102, "irfan", 25000);
e3.insert(103, "nakul", 55000);
e1.display();
e2.display();
e3.display();
}
}
上面代碼執(zhí)行得到結(jié)果如下 -
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
還有另一個維護Rectangle類記錄的例子。這里創(chuàng)建一個 TestRectangle1.java 類文件,代碼如下所示 -
class Rectangle {
int length;
int width;
void insert(int l, int w) {
length = l;
width = w;
}
void calculateArea() {
System.out.println(length * width);
}
}
class TestRectangle1 {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.insert(11, 5);
r2.insert(3, 15);
r1.calculateArea();
r2.calculateArea();
}
}
上面代碼執(zhí)行得到結(jié)果如下 -
55
45
在java中有很多方法可以用來創(chuàng)建對象。它們分別是:
new關(guān)鍵字newInstance()方法clone()方法在接下來的章節(jié)中,將學(xué)習(xí)這些方法用來創(chuàng)建對象。
匿名只是表示沒有名。沒有引用的對象(也就是不使用實例變量)稱為匿名對象。它只能在創(chuàng)建對象時使用。如果只需要使用一個對象,匿名對象是一個很好的方法。 例如:
new Calculation();//匿名對象
Calculation c = new Calculation();// 使用實例變量,所以不是匿名對象
調(diào)用方法通過引用:
Calculation c = new Calculation();
c.fact(5);
通過匿名對象調(diào)用方法:
new Calculation().fact(5);
下面來看看java中的匿名對象的完整示例。
class Calculation {
void fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("factorial is " + fact);
}
public static void main(String args[]) {
new Calculation().fact(5);// calling method with anonymous object
}
}
上面代碼執(zhí)行得到結(jié)果如下 -
Factorial is 120
可以按照一種類型創(chuàng)建多個對象,就像在原始數(shù)據(jù)類型中的情況中一樣。
原始變量的初始化:
int a=10, b=20;
引用變量的初始化:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
下面再看看一個例子:
class Rectangle {
int length;
int width;
void insert(int l, int w) {
length = l;
width = w;
}
void calculateArea() {
System.out.println(length * width);
}
}
class TestRectangle2 {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(), r2 = new Rectangle();// creating two
// objects
r1.insert(11, 5);
r2.insert(3, 15);
r1.calculateArea();
r2.calculateArea();
}
}
上面代碼執(zhí)行得到結(jié)果如下 -
55
45
在本節(jié)的最后部分,我們來看看一個真實應(yīng)用中的示例,模擬銀行賬戶轉(zhuǎn)帳的實現(xiàn)。這里創(chuàng)建一個 TestAccount.java 類文件,代碼如下所示 -
class Account {
int acc_no;
String name;
float amount;
void insert(int a, String n, float amt) {
acc_no = a;
name = n;
amount = amt;
}
void deposit(float amt) {
amount = amount + amt;
System.out.println(amt + " deposited");
}
void withdraw(float amt) {
if (amount < amt) {
System.out.println("Insufficient Balance");
} else {
amount = amount - amt;
System.out.println(amt + " withdrawn");
}
}
void checkBalance() {
System.out.println("Balance is: " + amount);
}
void display() {
System.out.println(acc_no + " " + name + " " + amount);
}
}
class TestAccount {
public static void main(String[] args) {
Account a1 = new Account();
a1.insert(832345, "Ankit", 1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}
}
上面代碼執(zhí)行得到結(jié)果如下 -
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0