What is the idea of ​​accessing private attributes inside the main? Java x C ++

When using C ++, access to a private attribute inside the main function is not allowed. Example:

#include <iostream>
using namespace std;
class Test {
    private: int a;
    public:
       Test(int value) { a = value; }
       int getValue() { return a; }
};
int main (int argc, char *argv[]) { 
    Test test2(4);
    cout << test2.a; // Compile error! Test::a is private within this context
    cout << test2.getValue(); // OK!
    return 0;
}

It is clear why an error occurs when accessing private attributes outside the class methods, since C ++ does not have basic functions inside classes.

However, in Java it is allowed:

public class Test {
    private int a;
    public Test(int value) { a = value; }
    public int getValue() { return a; }
    public static void main (String args[]) { 
        Test test1 = new Test(4);
        System.out.println(test1.a);
    }
}

I understand that in this case, main is INSIDE for the Test class. However, I cannot understand the idea of ​​why this is allowed, and what is the impact of this on code development / management.

When I learn C ++, I once heard: "Classes should not have a main one. The main action is with or uses class instances."

Can someone shed light on this issue?

+5
source share
5 answers

. , main . Java "". , ++ , Java , . (- ++) , , .

, Java , , VM , ( ) . , ++ ( )

+6

++ :

class Test {
    private: int a;
    public:
       Test(int value) { a = value; }
       int getValue() { return a; }
       static void Main()
       {
          Test t(10);
          cout << t.a;
       }
};

: private .

, .

. , ?

, , . . , . , ++ friend, .

+5

. Java, main Test. ++, , :

class Test2 {

    private int a;
    public Test(int value) { a = value; }
    public int getValue() { return a; }

}

public class Test {

    public static void main (String args[]) { 
        Test2 test2 = new Test2(4);
        System.out.println(test2.a); // does not compile
    }
}

, ++ , Java .

+2

private Java " " c.f. . , , .

AFAIK. , .

public interface MyApp {
    class Runner {
        public static void main(String... args) {
            // access a private member of another class
            // in the same file, but not nested.
            SomeEnum.VALUE1.value = "Hello World"; 
            System.out.println(SomeEnum.VALUE1);
        }
    }

    enum SomeEnum {
        VALUE1("value1"),
        VALUE2("value2"),
        VALUE3("value3");
        private String value;

        SomeEnum(final String value) {
            this.value = value;
        }
        public String toString() {
            return value;
        }
    }
}

http://vanillajava.blogspot.com/#!/2012/02/outer-class-local-access.html

+1

: Java - Object Oriented Programming, java, .

0

All Articles