-4

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?

Community
  • 1
  • 1
Mark
  • 684
  • 2
  • 9
  • 25
  • 2
    `MyClass myClass = new MyClass(varA, varB);` – Keiwan Nov 11 '16 at 21:14
  • non static varA and varB cannot be referenced from a static context :S – Mark Nov 11 '16 at 21:19
  • 2
    `varA` and `varB` are fields of `MyClass` instances, so why do you think it would make sense to use them ***before*** you created an instance? These fields aren't there, yet. – Tom Nov 11 '16 at 21:21
  • Daaaaaaaaaaaaamn!!!!! You're right,,, I was sure about it was a litle step.... dam, I'mGetting it now! – Mark Nov 11 '16 at 21:23

3 Answers3

2

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).

Vasu
  • 21,832
  • 11
  • 51
  • 67
  • varA and varB are already defined so: non static varA and varB cannot be referenced from a static context :S – Mark Nov 11 '16 at 21:20
  • With a little (but important) help from @Tom, I'm getting my little point... That's the answer. – Mark Nov 11 '16 at 21:25
1

I hope this answer will be helpful for you to understand why main method is static in non-static class

Why is the Java main method static?

Also, in code :

MyClass myClass = new MyClass(varA, varC);

Create new instance of you class using public constructor with your own parameters list.

Community
  • 1
  • 1
1

Agree with JavaGuy. Just for your clarity's sake, main method is made static so that it can be called from JVM without instantiation of the class. Hence to access any non static member of the class you need to have an instance of the class as mentioned by above solution by JavaGuy.