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();//非静态方法隶属于实例,实例化后调用
            
        }
    }
  • 相关阅读:
    20120109_1
    .NET(C#)开源代码分析
    Vue filter API All In One
    js 千位分隔符 All In One
    css fontfeaturesettings All In One
    vue 子组件不使用 watch 如何更新组件 All In One
    miro whiteboard All In One
    转载:sql注入的危害(登陆并获取数据库的名字,表的名称和字段)
    Windows 7/windows server 2008 R2 64位版IIS不能连接Access数据库,80004005报错的解决办法
    LINQ如何做SELECT TOP操作
  • 原文地址:https://www.cnblogs.com/Unlimited-Rain/p/12465310.html
Copyright © 2011-2022 走看看