How to create an object from the class in subdirectory in Java

YoungMin Park :

I started studying Java.
One part I got stuck is about how to create and use object which is originated from other class.

Directory structure:

/temp_dir/Java_code  
  Main.java  
  /java_db_code/  
    User_Table.java   

Source codes are like these.

// File: /temp_dir/Java_code/Main.java

package temp_dir.java_code; // Package configuration of this java file
import temp_dir.java_code.java_db_code.User_Table; // import other class

public class Main
{
  public static void main(String[] args)
  {
      int temp=5;

      // Create obj_user_table object from User_Table class located in package of temp_dir.java_code.java_db_code.User_Table, through its int parameterized constructor
      User_Table obj_user_table=new User_Table(temp);

      System.out.println(obj_user_table);
      // Expected: obj_user_table object

      System.out.println(obj_user_table.user_a);
      // Expected: 5
  }
}
// File: /temp_dir/Java_code/java_db_code/User_Table.java

package temp_dir.java_code.java_db_code;

public class User_Table
{
  public User_table(int a)
  {
    this.user_a=a;
  }
}

Run

cd /temp_dir/Java_code
javac -d . Main.java ./java_db_code/User_Table.java

Error

./java_db_code/User_Table.java:22: error: invalid method declaration; return type required
  public User_table(int a)
         ^
1 error

I wrote public User_table(int a) in User_Table.java as the constructor
But I don't know why error says that invalid method declaration; return type required

eric.m :

Method names are case sensitive: User_table is not the same as User_Table (notice the capital T). The constructor must have the same exact name as the class, so use User_Table.

Still, the compiler will complain about one other thing once you fix that: in the constructor you do

this.user_a=a;

But user_a is not declared in your class, which will make the compiler throw an error. To fix that, you just have to declare it in the class; since you want to access the field outside the class (for example, in Main.main()) make it public:

public class User_Table
{
  public int user_a;

  public User_table(int a)
  {
    this.user_a=a;
  }
}

As a recommendation, you should really consider following the Java naming and style conventions: - You should use more whitespaces: this.user_a = a, int temp = 5, obj_user_table = new - Class names use the UpperCamelCase, with no underscores: UserTable - Method and variable names use the lowerCamelCase, with no underscores: userA

This won't change the functionality of the code, but it will make it more readable and standard for other Java users.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326186&siteId=1