vasanth0989 / prep-myself

0 stars 0 forks source link

Java Classpath basics #13

Open vasanth0989 opened 9 months ago

vasanth0989 commented 9 months ago

Image

vasanth0989 commented 9 months ago

Sure, here's an example of how you can create a simple Java project with multiple packages:

First, let's create the directory structure for our project:

css Copy code myproject/ └── src ├── com │ └── example │ ├── Main.java │ └── util │ └── Utils.java └── org └── example └── helper └── Helper.java Here, we have three packages: com.example, com.example.util, and org.example.helper. Each package contains one Java file.

Contents of Main.java:

java Copy code package com.example;

import com.example.util.Utils; import org.example.helper.Helper;

public class Main { public static void main(String[] args) { Utils.printMessage(); Helper.help(); } } Contents of Utils.java:

java Copy code package com.example.util;

public class Utils { public static void printMessage() { System.out.println("Hello from Utils class!"); } } Contents of Helper.java:

java Copy code package org.example.helper;

public class Helper { public static void help() { System.out.println("Hello from Helper class!"); } } To compile these files, you would navigate to the src directory and run:

bash Copy code javac -d ../bin com/example/Main.java org/example/helper/Helper.java com/example/util/Utils.java This will compile all the Java files and place the compiled .class files in a bin directory (you can name it whatever you like).

To run the Main class from the com.example package using the -cp option, you would navigate to the parent directory of bin and run:

bash Copy code java -cp bin com.example.Main This command tells Java to use the bin directory as the classpath and run the Main class from the com.example package.