-1

I have the following code :

public class My_program {

    class dbConnect {
       public dbConnect();
       public void connect_to_db(String connect_string) {
          Class.forName(...);
          ...
       }
    }

    public static void main(String[] args) {
       String connect_string = "jdbc...";
       dbConnect db = new dbConnect();
       db.connect_to_db(connect_string)
    }
}

When I try to compile it, the following error occurs :

error: non-static variable this cannot be referenced from a static context

so I tried to make the dbConnect static like this : static class dbConnect and it's working ok but java is generating an extra .class file : My_program$dbConnect.class that I do not want.

So how can I have a single .class file and get the code to work .

Nitin Chhajer
  • 2,299
  • 1
  • 24
  • 35
pufos
  • 2,890
  • 8
  • 34
  • 38
  • 3
    possible duplicate of [Why do I get "non-static variable this cannot be referenced from a static context"?](http://stackoverflow.com/questions/10301907/why-do-i-get-non-static-variable-this-cannot-be-referenced-from-a-static-contex) – Jon Skeet Apr 25 '12 at 08:27
  • if you have 2 classes in a java file, you will have two .class files. Irrespective of whether the inner class is static or not. – krishnakumarp Apr 25 '12 at 08:27
  • why do you need the dbconnect class in the first place. Just use it's method as a My_program class method – Fofole Apr 25 '12 at 08:33
  • `java is generating an extra .class file that I DO NOT WANT` - may I wonder, why do you not want it? – bezmax Apr 25 '12 at 10:34

4 Answers4

3

one way depending on your requirement:

public class My_program {

My_program() { }


public void connect_to_db(String connect_string) {
      Class.forName(...);
      ......
   }

public static void main(String[] args) {
   String connect_string = "jdbc......";
   My_program db = new My_program();
   db.connect_to_db(connect_string)
}

}

Farid
  • 2,265
  • 18
  • 14
0
My_program$dbConnect.class 

This is the class file for inner class. If you create an inner class after compiling you will get a class file as

outerclass$innerclass.class
Dheeraj Joshi
  • 3,057
  • 8
  • 38
  • 55
0

you cant, the extra .class file will be generated. In java every class when compiled into byte code will generate a .class file. so your dbConnect class will generate a .class file.

Note: The first time the compilation failed thats why it didnt generate a Parent$dbconnect.class file

if you want only 1 .class file, then remove the inner class and put the logic inside your Parent class.

Rajesh Pantula
  • 10,061
  • 9
  • 43
  • 52
0

There is no way you will get one class file from two classes. That's how Java works.

You need to merge the contents of those two classes into one.

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48