静态变量

【公共的存储单元,类里任何一个对象访问它时,取到的都是相同的值】

 1 package DemoArea5.copy;
 2 
 3 import org.omg.PortableServer.POAPackage.ServantAlreadyActive;
 4 
 5 public class area5 {
 6     private int A;
 7     private int B;
 8     private String Color;
 9     public static int num=0;
10     
11     
12     public area5(int a,int b,String col) {
13         // 定义有参的构造方法
14         A=a;
15         B=b;
16         Color=col;
17         num++;//当构造方法被调用时num++
18         //次数的记录取决于实例化对象的语句次序,
19         //若连续实例化两个对象,则此时的num是2,若分开则会出现1、2
20     }
21     
22     int showarea(){
23         return A*B;
24     }
25     String showcolor(){
26         return Color;
27     }
28     String count(){
29         return"访问了"+num+"次";
30     }
31 }
package DemoArea5.copy;

public class Mainarea5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        area5 a1=new area5(3,12,"hS");// 第一次调用
        //area5 a2=new area5(3,6,"了LS");// 第二次调用
        
        System.out.println("A1"+a1.showarea());
        System.out.println("A1"+a1.showcolor());
        System.out.println("A1"+a1.count());
        
        area5 a2=new area5(3,6,"了LS");// 第二次调用
        System.out.println("A2"+a2.showarea());
        System.out.println("A2"+a2.showcolor());
        System.out.println("A2"+a2.count());
    }

}

结果

A136
A1hS
A1访问了1次
A218
A2了LS
A2访问了2次

、、、、、、、、、、、、、、、、、、、、、、、

A136
A1hS
A1访问了2次
A218
A2了LS
A2访问了2次

原文地址:https://www.cnblogs.com/dede-6/p/11899671.html