Multiple public classes in the same .java file

Even if one subclass the other one

Page 1 of 1

3 Replies - 3971 Views - Last Post: 30 March 2010 - 09:48 PM Rate Topic: -----

#1 kevin2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 02-November 09

Multiple public classes in the same .java file

Posted 30 March 2010 - 10:14 AM

I asked a question before, but I don't think it was clear enough. I'm using Netbeans IDE to develop java applications. I'm experienced more with C++. The following is an example of my code (that will not compile).

package helloworld;

public class simple {
public int iTst;
public float fcalc;
}

public class easy extends simple {
public int iMy;
public float fEsy;
}

When I try to compile this code i get a message indicating that class simple should be in a file (test.simple). I find this confusiong since 1) the class is declared locally 2) the class is named simple (not test.simple).

Is it possible to compile and run this code with class simple begin a part of this file or do I have to put it in another file ?

This post has been edited by pbl: 30 March 2010 - 09:50 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Multiple public classes in the same .java file

#2 Galois  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 207
  • Joined: 27-March 10

Re: Multiple public classes in the same .java file

Posted 30 March 2010 - 10:19 AM

You cannot have 2 public classes in a single file, because that would defeat the whole purpose of having spreading a program into modules. Delete the "public" keyword from one of the classes to fix this issue.
Was This Post Helpful? 0
  • +
  • -

#3 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Multiple public classes in the same .java file

Posted 30 March 2010 - 10:22 AM

in java each public class should be declared in a different file.
so, have one file named simple.java:

package helloworld 

public class simple {
  public int iTst;
  public float fcalc;
}


and a second file, easy.java:

package helloworld;
public class easy {
  public int iMy;
  public float fEsy;
}


or, else, you can do something like:
package helloworld;

public class simple {
public int iTst;
public float fcalc;
}

class easy extends simple {
public int iMy;
public float fEsy;
}


notice that in this code, easy is not declared as public, so it gets the "default" acces level.
Was This Post Helpful? 1
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Multiple public classes in the same .java file

Posted 30 March 2010 - 09:48 PM

and so we do not need the annoying C++ .h file
Topic title renamed to be more descriptive
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1