在java类 的main方法中申明该类的对象,在对象中可以访问私有变量或方法,为什么?

解决方案 »

  1.   

    这个main方法其实就是这个类的方法,当然可以访问这个类的私有变量和方法
      

  2.   

    because it is one of the class methods of the class and the variable or method which will be called must be static type
      

  3.   

    看这个例子
    public class ExPrivate {
      private String s ;
      
      public ExPrivate( String s ) {
        this.s = s ;
      }  public getS() {
        return s ;
      }  public static int main( String args[] ) {
        ExPrivate obj = new ExPrivate( "Big0bike" ) ;
        System.out.println( obj.s ) ; // 这个可以,但不提倡,访问field应该用getters
        ExOther ex = new ExOther( "Nothing" ) ;
        // System.out.println( ex.s ) ; // 这个是不行的,而是:
        System.out.println( ex.getS ) ;
      }}class ExOther {
      private String s ;
      
      public ExOther( String s ) {
        this.s = s ;
      }  public String getS() {
        return s ;
      }
    }
      

  4.   

    package examples;/**
     *
     * @author Administrator
     */
    public class Test {
        
        /** Creates a new instance of Test */
        public Test() {
        }
        private void alt(){
            System.out.print("==================");
        }
        private int tt=0;
        
        public static void main(String[] args){
           Test aa= new Test();
    ///下面是对的为什么
           System.out.println("=="+aa.tt);
           aa.alt();
        }
        
    }
      

  5.   

    楼主,上面不是已经解释了么???怎么还问啊?main()方法是Test类的方法,当然可以访问本类的所有成员(包括private成员)!
      

  6.   

    类的成员函数难道不能访问自己的私有变量么??
    private void alt()
     public static void main
    这两者对于类Test来说是一样的啊
    这是一个是私有方法
    一个是公有静态方法
      

  7.   

    不是这个意思啊。
    Test aa= new Test();
    这一句,我构造了一个对象啊
    然后是这是对象的私有方法
      

  8.   

    一个类对象可以访问本类所有对象的私有域或私有方法,即若a是Test的对象,b也是Test的对象,a可以访问b的私有域或私有方法,b也可以访问a的私有域或私有方法。
    不知道解释清楚没有~~
      

  9.   

    你的类是公有的public  所以可以通过类访问类里面的对象 但是不能 单独访问
      

  10.   

    楼主的问题关键是你的对象是在类内,所以可以访问private变量
    如果在类外就不可以了。
    其它的别人已经解释了。希望你明白。
      

  11.   

    上面已全解释清楚了,
    楼主应该明白了,帮你顶策群网络学院
    www.cequn.com
      

  12.   

    main方法其实不属于任何一个类,但如果写在某个类中,这时它就可以访问该类的私有方法及属性。
      

  13.   

    private是相对于类而言的,不是对对象而言的。
      

  14.   

    此时main方法为该类的一个静态方法,可以把它理解类中的普通的静态方法。
    多说一点Java和C++不同,它是一种纯面向对象的语言,在代码中不准出现独立于面向对象的成份,并且每一个应用程序都要有一个执行它的入口地址。这就是为什么会有main方法