-1
// The "Tester" class.

import java.applet.*;  
import java.awt.*;


public class Tester

{

        public static void main (String[] args)
        {
            ThreadTest ex1 = new ThreadTest ();
            ThreadTest2 ex2 = new ThreadTest2 ();
            ex1.start ();
            ex2.start ();
        }
} //Tester class

public class ThreadTest extends Thread

{

       public ThreadTest ()

       {
       }

       public void run ()
       {
          while (true)
          {
              System.out.println ("Hello");
              delay (1000);
          }
       }


        public void delay (int num)
        {
            Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
            try
            {
                Thread.sleep (num);
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace ();
            }
            Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);
        }
} // ThreadTest class

public class ThreadTest2 extends Thread //This is where the error is

{

        public ThreadTest2 ()
        {
        }


        public void run ()
        {
            while (true)
            {
                System.out.println ("Hello2");
                delay (1000);
            }
        }


        public void delay (int num)
        {
            Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
            try
            {
                Thread.sleep (num);
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace ();
            }`enter code here
            Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);
        }
} // ThreadTest2 class

I don't understand the error that pops up every time i try to run the code. The error that pops up is

"The type "ThreadTest2" is declared public in compliation unit "G:/Java/newstuff/Tester.java" which also contains the public type, "Tester""

takendarkk
  • 3,347
  • 8
  • 25
  • 37
Jade
  • 71
  • 1
  • 12

3 Answers3

2

Java rules are that you can have only one top level public class in a file, and its name must match that of the file. Why this is so, I don't know, but I do know that it is the rules that must be obeyed.

See the Java 1.7 JLS 7.6 for more details.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

You should have only one public class per file in Java. The filename should be the same as class name plus .java extension.

In your case you should have 2 files:

  • Tester.java with Tester class

  • ThreadTest.java with ThreadTest class

Szymon
  • 42,577
  • 16
  • 96
  • 114
0

It's a matter of style and readability. The only public class in a .java file also has to be the name of the file.

Read more:

Can a java file have more than one class?

Community
  • 1
  • 1
GriffinG
  • 662
  • 4
  • 13