静态方法

【用static修饰的方法叫做静态方法】

【static方法是属于整个类的不被某个对象所专用】

【不能直接操作所以只能调用或者访问成员变量】

【在静态方法中不能使用THIS,SUPER】

package DemoArea6.copy;

import org.omg.PortableServer.POAPackage.ServantAlreadyActive;

public class area6 {
    private int A;
    private int B;
    private String Color;
    public static int num=0;
    
    
    public area6(int a,int b,String col) {
        // 定义有参的构造方法
        A=a;
        B=b;
        Color=col;
        num++;//当构造方法被调用时num++
        //次数的记录取决于实例化对象的语句次序,
        //若连续实例化两个对象,则此时的num是2,若分开则会出现1、2
    }
    
    int showarea(){
        return A*B;
    }
    String showcolor(){
        return Color;
    }
    public static void count(){
        //声明count是静态方法
        
        System.out.println("访问了"+num+"次");
        
    }
}
 1 package DemoArea6.copy;
 2 
 3 public class Mainarea6 {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         
 8         area6.count();//直接用类名调用,可
 9         area6 a1=new area6(3,12,"hS");// 第一次调用
10         area6 a2=new area6(3,6,"了LS");// 第二次调用
11         
12         System.out.println("A1"+a1.showarea());
13         System.out.println("A1"+a1.showcolor());
14         //System.out.println("A1"+a1.count());//这样它就会显示错误
15         a1.count();//用实例化对象调用,可
16         
17         //area5 a2=new area5(3,6,"了LS");// 第二次调用
18         System.out.println("A2"+a2.showarea());
19         System.out.println("A2"+a2.showcolor());
20         a2.count();
21         
22         area6 a3=new area6(1,2,"hh");// 第三次调用
23         a3.count();
24     }
25 
26 }
原文地址:https://www.cnblogs.com/dede-6/p/11899772.html