How to compile several classes in one ,java file

123 Views Asked by At

I would like to compile in a java source file with two classes. How can I do that? I compile my code with:

javac -classpath Class_ex_1.java
public class Class_ex_1 { 
    public static void main(String[] args) {        
        int del = 7;
        int del_1 = 2;
        int rem = del % del_1;
        System.out.println("First value :" + del + "\n");
        System.out.println("Second value :" + del_1 + "\n"); // 
        System.out.println("Display meaning a % b :" + rem + "\n"); //              
            
        Hello_test n1 = new Hello_test();
        System.out.println("Display parameter from class:" + n1.getColor + "\n");
                        
    }
}
    
public class Hello_test {
    String color = "Red";       
    public String getColor(){
        return color;
    }           
}
2

There are 2 best solutions below

1
Drew On BEST ANSWER
class Hello_test{}

Simply remove public from the second class. Also make sure the other class is inside of the Class_ex_1

5
TheCreatingCoder On

The following code doesn't compile because it cannot find getColor

public class Class_ex_1 { 

   public static void main(String[] args) {        
      int del = 7;
      int del_1 = 2;
      int rem = del % del_1;
      System.out.println("First value :" + del + "\n");
      System.out.println("Second value :" + del_1 + "\n"); // 
      System.out.println("Display meaning a % b :" + rem + "\n"); //              
          
      Hello_test n1 = new Hello_test();
      System.out.println("Display parameter from class:" + n1.getColor + "\n");
                      
   }
}
    
class Hello_test {
   String color = "Red";       
   public String getColor(){
      return color;
   }           
}

So it should instead, look like the following:

class Class_ex_1 { 

 


   public static void main(String[] args) {        
      int del = 7;
      int del_1 = 2;
      int rem = del % del_1;
      System.out.println("First value :" + del + "\n");
      System.out.println("Second value :" + del_1 + "\n"); // 
      System.out.println("Display meaning a % b :" + rem + "\n"); //              
          
      Hello_test n1 = new Hello_test();
      System.out.println("Display parameter from class:" + n1.getColor() + "\n");
                      
   }
}
    
class Hello_test {
   String color = "Red";   
       
   public String getColor(){
      return color;
   }          
       

}

Remember that when we call a method, we need to have a set of parenthesis at the end.