Mark Mark - 9 months ago 35
Java Question

Yet another non static variable cannot be referenced issue

I've read this, and also this and I guess I'm getting the theroical point af static and non static content but I'm unable to apply it to the following case (which is supposed to work) May be so, so, so basic but... humans.

public class MyClass {

private String varA ;
private int varB;

public MyClass(String var, int var) throws SocketException {
//stuff to work with


private void methodA() {
//more stuff....

public static void main(String args[]) throws IOException {

//How to instatiate MyClass(varA,varC)?


So, how it's supposed to be instatiated MyClass from main if MyClass is not static?

Answer Source

How to instatiate MyClass(varA,varC) ?

public static void main(String args[]) throws IOException {

    //local variables
    String varA = "A";
    int varC = 10;

    //Use the constructor of the class to create an object
    MyClass myClassObj = new MyClass(varA, varC);

You always need to use the constructors provided by the class to instantiate a class. You don't have the default (no argument) constructor in your class, so you need to pass the constructor arguments as shown above to instantiate the class.

You can look here.

In your MyClass class instance variables varA, varB are created/maintained for each object(instance) separately.

Just to add, if there are any static variables present in a class, they will be maintained only per class (not for each object).