zoukankan      html  css  js  c++  java
  • [转]Java静态方法为什么不能访问非静态方法

    非静态方法(不带static)可以访问静态方法(带static),但是反过来就不行,为什么呢?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class test{
        public void static main(String args[]){
            method(); //会出错,提示你讲method方法改成静态的
            method2(); //调用方法正确
            new Test2().method(); //正确
        }
        public void method(){
            System.out.println("HelloWorld");
        }
        public static void method2(){
            System.out.println("HelloWorld");
        }
    }
    public class Test2{
        public void method(){
            System.out.println("HelloWorld");
        }
    }

    这个要从java的内存机制去分析,首先当你New 一个对象的时候,并不是先在堆中为对象开辟内存空间,而是先将类中的静态方法(带有static修饰的静态函数)的代码加载到一个叫做方法区的地方,然后 再在堆内存中创建对象。所以说静态方法会随着类的加载而被加载。当你new一个对象时,该对象存在于对内存中,this关键字一般指该对象,但是如果没有 new对象,而是通过类名调用该类的静态方法也可以。

    程序最终都是在内存中执行,变量只有在内存中占有一席之地时才会被访问,类的静态成员(变态和方法)属于类本身,在类加载的时候就会分配内存,可以 通过类名直接去访问,非静态成员(变量和方法)属于类的对象,所以只有在类的对象禅师(创建实例)的时候才会分配内存,然后通过类的对象去访问。

    在一个类的静态成员中去访问非静态成员之所以会出错是因为在类的非静态成员不存在的时候静态成员就已经存在了,访问一个内存中不存在的东西当然会出错。

    那类是什么时候被加载呢?在需要调用的时候被加载。

  • 相关阅读:
    【LeetCode】17. Letter Combinations of a Phone Number
    【LeetCode】16. 3Sum Closest
    【LeetCode】15. 3Sum 三个数和为0
    【LeetCode】14. Longest Common Prefix 最长前缀子串
    【LeetCode】13. Roman to Integer 罗马数字转整数
    【LeetCode】12. Integer to Roman 整型数转罗马数
    【LeetCode】11. Container With Most Water
    【LeetCode】10. Regular Expression Matching
    Models of good programmer
    RSA Algorithm
  • 原文地址:https://www.cnblogs.com/dirgo/p/4897942.html
Copyright © 2011-2022 走看看