static

本文阅读 2 分钟
首页 代码,Java 正文

1.静态成员方法

静态成员方法是由static修饰,类和对象共享。 访问格式: 1.类名.静态成员方法 2.对象.静态成员方法

2.实例成员方法

不用static修饰,属于对象。 访问格式: 对象.实例成员方法

package com.staticTest;
//static访问注意事项
public class Test1 { 
    //静态成员
    public static int id;
    public static void two(){ 
        System.out.println("two");
    }
    //实例成员
    public String name;
    public void three(){ 
        System.out.println("three");
    }

    //1.静态方法只能访问静态成员,不可以直接访问实例成员
    public static void one(){ 
        System.out.println(Test1.id);
        System.out.println(id);  //在同一个类中,类名可以省略。
        Test1.two();
        two();
        //System.out.println(name); 不能直接访问实例成员
        //可以间接访问
        Test1 t=new Test1();
        System.out.println(t.name);
        //three(); 不能直接访问实例成员
        t.three();
    }

    //2.实例方法可以访问静态成员,也可以访问实例成员
    public void four(){ 
        System.out.println(Test1.id);
        System.out.println(name);
        one();
        three();
    }
    //3.静态方法中不能出现this关键字
    public static void five(){ 
        //System.out.println(this);
    }
    public static void main(String[] args) { 

    }
}
package com.staticTest;

import java.util.ArrayList;

public class Test2 { 
    //1.定义一个静态集合
    public static ArrayList<String> cards=new ArrayList<>();
    //2.在main方法执行前,把54张牌放进去
    static { 
        //3.做牌,放到集合
        //定义一个数组存储全部点数
        String [] num={ "A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        //定义一个数组存储全部花色
        String [] colors={ "♥","♠","♦","♣"};
        //遍历点数
        for (int i = 0; i < num.length; i++) { 
            //遍历花色
            for (int j = 0; j < colors.length; j++) { 
                //一张牌
                String card=num[i]+colors[j];
                //添加到集合中
                cards.add(card);
            }
        }
        //加入大小王
        cards.add("大王");
        cards.add("小王");
    }

    public static void main(String[] args) { 
        System.out.println(cards);
    }
}
/* [A♥, A♠, A♦, A♣, 2♥, 2♠, 2♦, 2♣, 3♥, 3♠, 3♦, 3♣, 4♥, 4♠, 4♦, 4♣, 5♥, 5♠, 5♦, 5♣, 6♥, 6♠, 6♦, 6♣, 7♥, 7♠, 7♦, 7♣, 8♥, 8♠, 8♦, 8♣, 9♥, 9♠, 9♦, 9♣, 10♥, 10♠, 10♦, 10♣, J♥, J♠, J♦, J♣, Q♥, Q♠, Q♦, Q♣, K♥, K♠, K♦, K♣, 大王, 小王] */
本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/qq_43514330/article/details/125085748
-- 展开阅读全文 --
安全面试之XSS(跨站脚本攻击)
« 上一篇 07-24

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复