面向对象_static关键字的引入

来源:互联网 发布:java ee api 怎么下载 编辑:程序博客网 时间:2024/06/06 08:47
/*
定义一个人类

姓名和年龄都是变化的,唯独国籍是一样的
一样的国籍,每次创建对象,在堆内存都要开辟同样的空间,
浪费了。怎么办呢?
针对多个对象有共同的这样的成员变量值的时候,
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();

}
0 0
原创粉丝点击