?? person1.java
字號:
//【例3.4】 實例成員與類成員。
//【例3.5】 類的繼承性。
//【例3.6】 類中方法的多態性。
//【例3.7】 運行時多態性的應用。
public class Person1
{
protected String name; //姓名,實例成員變量,保護成員
protected int age; //年齡
protected static int count=0; //人數,類成員變量,本類及子類對象計數
public Person1(String name,int age) //構造方法
{
this.set(name);
this.set(age);
count++; //人數增1
}
public Person1(String name) //構造方法重載
{
this(name,0); //調用本類的構造方法
}
public Person1() //構造方法重載
{
this("姓名未知",0);
}
public Person1(Person1 p1) //構造方法重載
{
this(p1.name, p1.age);
}
public void finalize() //析構方法
{
System.out.println("釋放對象 ("+this.toString()+")");
//調用實例成員方法
this.count--; //人數減1
}
public void set(String name) //設置成員變量值
{
if (name==null || name=="")
this.name = "姓名未知";
else
this.name = name;
}
public void set(int age)
{
if (age>0 && age<100)
this.age = age;
else
this.age = 0;
}
public void set(String name, int age)
{
this.set(name);
this.set(age);
}
public void set(Person1 p1)
{
this.set(p1.name);
this.set(p1.age);
}
public String getName() //獲得成員變量值
{
return this.name;
}
public int getAge()
{
return this.age;
}
public static void howMany() //類成員方法,只能訪問類成員變量
{
System.out.print("Person1.count="+count+" ");
}
public String belongClassName()
{
String str=""; //局部變量,不能使用修飾符
if (this instanceof Person1) //判斷當前對象是否屬于Person1類
str="Person1";
return str;
}
public String toString()
{
return this.name+","+this.age+"歲";
}
public void print() //實例成員方法,可以訪問類成員變量和實例成員變量
{
this.howMany(); //通過對象調用類成員方法
System.out.println(this.belongClassName()+"類 ("+this.toString()+")");
//通過對象調用實例成員方法
}
public int olderThen(Person1 p2) //比較兩個人的年齡
{
return this.age - p2.age;
}
public boolean equals(Object obj) //覆蓋Object類中方法
{
if (this == obj)
{
return true;
}
if (obj instanceof Person1)
{
Person1 p1 = (Person1)obj;
return this.name.equals(p1.name) && this.age==p1.age;
}
return false;
}
public static void main(String args[]) //main方法也是類成員方法
{
Person1 p1 = new Person1("李小明",21);
p1.print();
Person1 p2 = new Person1("王大偉",19);
p2.print();
System.out.println(p1.getName()+" 比 "+p2.getName()+" 大 "+p1.olderThen(p2)+" 歲");
//通過對象調用實例成員方法
p1.finalize(); //調用對象的析構方法
p1 = null; //p1為空對象
Person1.howMany(); //通過類名調用類成員方法
System.out.println();
}
}
/*
程序運行結果如下:
Person1.count=1 Person1類 (李小明,21歲)
Person1.count=2 Person1類 (王大偉,19歲)
李小明 比 王大偉 大 2 歲
釋放對象 (李小明,21歲)
Person1.count=1
*/
/*
protected Date2 birthday; //出生日期
public int age() //年齡
{
return this.age - b.age;
}
程序正確:
1、當沒有創建任何對象時,輸出如下:
Person1.count=0
public void print()
{
System.out.println("本類名="+this.getClass().getName()+" "+
"超類名="+this.getClass().getSuperclass().getName()+" ");
}
System.out.println(this.getClass().getName()+"類 "+this.toString()); //可以調用實例方法
程序錯誤:
public static int howMany()
{
Person1 objp=this; //編譯錯,類方法中不能使用this引用, non-static variable this cannot be referenced from a static context
return count;
}
public String str=""; //編譯錯,局部變量,不能使用修飾符
static String str=""; //局部變量,不能使用修飾符
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -