javajarclasspath

How do I properly create a Library in Java?


I have just created a library that will store and add elements into Hashmap. I have generated a jar file , and placed it into the Desktop. How can i use my library and work with it , i have already placed it into library folder , but what next, how can i work with it ? any help pls Here is my library that i wan to use it i my project

//here is my Library code

public class Main {
    public Main() {
    }

    public static void main(String[] args) {
        Map<Integer, String> boombom = new HashMap();
        addElements1(boombom, 1, "XML serv.");
        printElements(boombom);
    }

    private static void printElements(Map<Integer, String> boombom) {
        System.out.println(boombom);
    }

    private static void addElements1(Map<Integer, String> boombom, int i, String s) {
        boombom.put(i, s);
    }
}


Solution

  • A library is essentially an extension to your codebase. Any classes that you add to it would be accessible in the rest of the project, where it was imported.

    Simply, Create your class, as you normally would in your main file, then just copy it over to your library file. Name the class the same as the file, to simplify matters.

    No need to overcomplicate things at this juncture in your learning path. I believe this should work. I have not tested this, however the fundamentals are correct.

    This is not a static library, thus, in order to be used, it must be instantiated, like so:

    MyLibrary myLibrary = new MyLibrary();
    

    Then, since the functions inside the class are public, you would be able to call them like this:

    myLibrary.addElements1(1, "ESPS");
    

    This method of coding is called Object Oriented Programming. There's a thousand and one mistakes here, but it would work.

    class MyLibrary {
        public Map<Integer, String> boombom;
    
        public void myLibrary() {
            boombom = new HashMap();
        }
    
        public void printElements() {
            System.out.println(boombom);
        }
    
        public void addElements1(int i, String s) {
            boombom.put(i, s);
        }
    }