1. 程式人生 > >建立一個類Student

建立一個類Student

package fgh;

public class Student {//建立類Student  
        String name;//資料型別的定義
        String sex;
        int age;
        public Student()//定義無參構造
        {
            name="張雪";
            sex="女";
            age=20;
        }
        public Student(String i,String x)//定義有參構造
        {
            name=i;
            sex=x;
        }
        public
Student(String i,String x,int v)//定義有參構造 { name=i; sex=x; age=v; } void shouInfo() { System.out.println("姓名:"+name); System.out.println("性別:"+sex); System.out.println("年齡:"+age); } public
static void main(String[] args) { // TODO Auto-generated method stub Student sc1=new Student(); System.out.println("第一個人的資訊"); sc1.shouInfo(); System.out.println("第二個人的資訊"); Student sc2=new Student("姜銘","男"); sc2.age=23; sc2.shouInfo(); Student sc3=new
Student("周易","女"); System.out.println("第三個人的資訊"); sc3.age=18; sc3.shouInfo(); } }

結果如下:
這裡寫圖片描述
知識點:建立了類Student的物件sc1、sc2和sc3,物件通過呼叫shoeInfo()實現物件屬性,物件sc1呼叫無參的構成方法、sc2呼叫兩個引數的構造方法、sc3呼叫有三個引數的構造方法。呼叫不同的構造方法可以實現物件不同的初始化。
心得體會:
方法的重寫是在繼承的過程中,子類重新繼承父類的成員方法,使得新定義的方法具有和父類的成員方法相同的方法名,引數和返回值,但是具有不同的方法體。因此,方法重寫可以在不同子類中的不同操作。一般來說,通過方法重寫,子類物件只會呼叫子類中定義的方法,而不會呼叫父類中的同名方法。