It is said that the following code violates the OO Guiding Principle.
public class Main {
public static String NAME = "James";
public Main() {
System.out.println("Name is: "+NAME);
}
}
public class AnotherMain() {
public AnotherMain() {
System.out.println("Print name: "+Main.NAME);
}
}
All I could guess is it could have an abstract class that has a concrete method of say print(String message) and then have the Main class and AnotherMain class to extend the abstract class and then pass their to-be-printed message into the print() method implemented in their parent abstract class. Then in their constructors, they would call print(“Name is: “+NAME). This would save the constructors from calling System.out.println() twice.
But I am still sceptical because it says that the code has something that violates the OO Guiding Principle.
Any suggestions for this?
Thanks.
Right off the top of my head,
violates encapsulation by accessing something owned by an independent class; if that is intended, then
NAMEshould be independent of both classes and imported into both their scopes.