天天看點

面向對象_static關鍵字的引入

/*

定義一個人類


姓名和年齡都是變化的,唯獨國籍是一樣的

一樣的國籍,每次建立對象,在堆記憶體都要開辟同樣的空間,

浪費了。怎麼辦呢?

針對多個對象有共同的這樣的成員變量值的時候,

Java就給我們提供了一個關鍵字來修飾:static。

 */

 class Person{

//姓名

String name;

//年齡

int age;

//國籍

//String country;

static String country;


public Person(){


}


public Person(String name,int age){

this.name = name;

this.age = age;

}


public Person(String name,int age,String country){

this.name = name;

this.age = age;

this.country = country;

}


public void show(){

System.out.println("姓名:"+name+",年齡:"+age+",國籍:"+country);

}

 }



 class PersonDemo{

public static void main(String[] args){

//建立對象1

Person p1 = new Person("鄧超",33,"中國");

p1.show();


//建立對象2

//Person p2 = new Person("陳赫",22,"中國");

//p2.show();

Person p2 = new Person("陳赫",22);

p2.show();


//建立對像3

//Person p2 = new Person("陳赫",22,"中國" );

//p2.show();

Person p3 = new Person("李金銘",18);

p3.show();


p3.country = "美國";

p3.show();


p1.show();

p2.show();

} 

 }