zoukankan      html  css  js  c++  java
  • static关键字——Java面向对象基础(6)

    一、static属性

      1.static关键字修饰的属性,它隶属于类,不依赖实例。用static修饰的属性我们称之为静态成员变量”或者”类成员变量”。

      2.没有用static关键字修饰的属性,它不隶属于类,依赖实例。这种方式我们称之为“实例成员”。

    public class My_math {
        static int mathScore1;//静态成员变量
        int mathScore2;//非静态成员变量
    }

      3.用static修饰的方法不能直接使用非static修饰的属性。要使用,必须将成员变量变为静态的成员变量。

    public class My_math {
        static int mathScore1;//静态成员变量
        int mathScore2;//非静态成员变量
        public static void showScore(){
            System.out.println(mathScore1);
            System.out.println(mathScore2);//报错
        }
    }

       4.普通方法可以直接使用当前类中成员变量(无论是static修饰与否都可以)

    package com.xhu.myhomework;
    public class My_math {
        static int mathScore1;//静态成员变量
        int mathScore2;//非静态成员变量
        public void showScore(){
            System.out.println(mathScore1);//不会报错
            System.out.println(mathScore2);//不会报错
        }
    }

    二、static方法

      1.非静态方法中可以调用静态方法、非静态方法

        public static void showScore(){
            System.out.println();
        }
        
        public void useScore(){
            showScore();//调用静态方法
        }

      2.静态方法中不能调用非静态方法

        public void useScore(){
            System.out.println();
        }
        public static void showScore(){
            useScore();//静态方法中调用非静态方法,报错
        }

    三、调用方法

      1.在同一个类中的方法可以直接写方法名调用(注意:静态方法和非静态方法的互调参见二

      2.在类外调用:

        当方法是非静态方法时,使用类名.方法名调用

        当方法时静态方法时,使用实例名.方法名调用

    public class My_math {
        
        public void useScore(){
            System.out.println();//非静态方法
        }
        public static void showScore(){
            System.out.println();//静态方法
        }
    }
    public class Main {
    
        public static void main(String[] args) {
            My_math m;
            My_math.showScore();//静态方法隶属于类,可以直接使用类名调用
            
            m=new My_math();
            m.useScore();//非静态方法隶属于实例,实例化后调用
            
        }
    }
  • 相关阅读:
    jquery实现选项卡(两句即可实现)
    常用特效积累
    jquery学习笔记
    idong常用js总结
    织梦添加幻灯片的方法
    LeetCode "Copy List with Random Pointer"
    LeetCode "Remove Nth Node From End of List"
    LeetCode "Sqrt(x)"
    LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"
    LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"
  • 原文地址:https://www.cnblogs.com/Unlimited-Rain/p/12465310.html
Copyright © 2011-2022 走看看