/*
* 類的定義:
* 類是用來描述現實世界的事物的
*
* 事物:
* 屬性 事物的描述信息
* 行為 事物能夠做什么
*
* 類是如何和事物進行對應的呢?
* 類:
* 成員變量
* 成員方法
*
* 需求:寫一個學生類
*
* 學生事物:
* 屬性:姓名,年齡...
* 行為:學習,吃飯...
*
* 學生類:
* 成員變量:姓名,年齡
* 成員方法:學習,吃飯
*
* 成員變量:和我們前面學習過的變量的定義是一樣的。
* 位置不同:類中,方法外
* 初始化值:不需要給初始化值
* 成員方法:和我們前面學習過的方法的定義是一樣的。
* 去掉static關鍵字
*/
public class Student { //成員變量 //姓名 String name; //年齡 int age; //成員方法 //學習的方法 public void study() { System.out.println("好好學習,天天向上"); } //吃飯的方法 public void eat() { System.out.println("學習餓了要吃飯"); } }
* 使用一個類,其實就是使用該類的成員。(成員變量和成員方法) * 而我們要想使用一個類的成員,就必須首先擁有該類的對象。 * 我們如何擁有一個類的對象呢? * 創建對象就可以了? * 我們如何創建對象呢? * 格式:類名 對象名 = new 類名(); * 對象如何訪問成員呢? * 成員變量:對象名.變量名 * 成員方法:對象名.方法名(...) */ public class StudentDemo { public static void main(String[] args) { //格式:類名 對象名 = new 類名(); Student s = new Student(); //System.out.println("s:"+s); //com.itheima_02.Student@193c0cf //直接輸出成員變量值 System.out.println("姓名:"+s.name); //null System.out.println("年齡:"+s.age); //0 System.out.println("----------"); //給成員變量賦值 s.name = "林青霞"; s.age = 28; //再次輸出成員變量的值 System.out.println("姓名:"+s.name); //林青霞 System.out.println("年齡:"+s.age); //28 System.out.println("----------"); //調用成員方法 s.study(); s.eat(); } }
輸出如下