Calling One Constructor from Another
This example calls one constructor from another constructor in Java.
There are two constructors inside the Two
class.
Inside the first constructor, we have used this
keyword to call the second constructor.
The second constructor is called from the first constructor by passing arguments.
†Note that the line inside a constructor that calls another constructor should be the first line of the constructor; i.e., this(a,b)
should be the first line of Two()
.
Also, we cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.
An instance variable, as the name suggests is tied to an instance of a class.
Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn’t make sense.
Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.