When using C++ one is not allowed to access a private attribute inside a main function. 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 there is an error when accessing private attributes outside class methods, since C++ do not have main 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 in this case main is INSIDE the Test class. However, I cannot understand the idea WHY is this allowed, and what is the impact of this in the development/management of the code.
When learning C++, I once heard “Classes shouldn’t have a main. Main acts with or uses instances of classes”.
Can someone shed some light on this question?
You are looking at this from the wrong point of view. The question is not why main can acces the class internals. There is not one ‘main’ in Java. The important difference to this respect is that for C++ there is a single entry point into the application that is main, while in Java a single application can have multiple entry points, as many as one per class. The entry point must be a static method (member function in C++ jargon) of a class with a particular signature, and the behavior is exactly the same as for other static methods of the same class.
The reason that Java can have multiple entry points is that you tell the VM on startup where (what class) you want to start your application in. That is a feature that is not available in C++ (and many other languages)