面向对象数组

 格式:类 对象数组名称[] = new 类[数组长度];

这个类可以产生实例

class Person{

private String name;

public Person(String name)

{ // 通过构造方法设置内容 this.name = name; // 为姓名赋值 }

public String getName()

{ // 取得姓名 return this.name; }

}

 

public class Test{ public static void main(String[] args) {

Person per[] = new Person[3]; // 声明一个对象数组,里面包含3个对象

System.out.println("====数组声明===="); 

for(int x=0;x<per.length;x++){ ​ System.out.println(per[x] + "、"); ​ } ​ //分别为数组中的每个元素初始化,每一个都是对象,都需要单独实例化 

per[0] = new Person("张三"); 

per[1] = new Person("张四"); 

​ per[2] = new Person("张五");    多态以后要用到

System.out.println("====对象实例化===="); 

for (int x=0;x<per.length;x++)

{ ​ System.out.println(per[x].getName() + "、"); 

} ​ } }

然后是加了static的变量

public static int x=7;//共享拷贝
public int y=3;
public static void main(String[] args) {//加了static后就是,最后的赋值a的值
IdentifyMyParts a = new IdentifyMyParts();
IdentifyMyParts b = new IdentifyMyParts();

a.x=1;
b.x=2;

System.out.println(a.x);

System.out.println(IdentifyMyParts.x);

 

 

反思:static添加后是静态变量,变量共享一个地址,与 实例变量不一样。

 

posted @ 2021-10-19 23:34  冯三权  阅读(51)  评论(0)    收藏  举报