Bootstrap FreeKB - Java - Understanding package
Java - Understanding package

Updated:   |  Java articles

class is a collection of markup that performs a certain function. To use an analogy, the military has a class of officers classifed as privates, and a different class of officers classified as admirals. When combat is needed, the officers from the privates class will be used. When negotiation is needed, the officers from the admirals class will be used. In the same way, when a Java programs needs to do something, a class is used.

Let's say you've created a class called Hello.java (in Eclipse in this example). 

 

In this example, the Hello.java class is in the my.pkg package. There is a public static void method called main that will print Hello World.

package my.pkg;

public class Hello {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

 


Using the method in another class

Here is how you could use the main method in the Hello class in the my.pkg package in another class. In this scenario, you would reference the method as <package>.<class>.<method>.

public class World {
	public static void main(String[] args) {
		my.pkg.Hello.main();
	}
}

 


Using the method in a JSP page

Let's say you have the following class in the my.pkg package.

package my.pkg;

public class Hello {
	public static String main() {
		return "Hello World";
	}
}

 

At the top of a JSP page, you would import the class using <package>.<class>.

<%@page import="my.pkg.Hello"%>

 

In the <body> of the JSP page, you could then use the method like this.

  • In this example, Hello is the name of the class (e.g. public class Hello)
  • In this example, example is any custom text you want to use
  • In this example, main is the name of the method (e.g. public static String main)
<%
  Hello example = new Hello();
  out.print(example.main());
%>

 

Here is an example of a JSP page.

<%@page import="my.pkg.Hello"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
  Hello example = new Hello();
  out.print(example.main());
%>
</body>
</html>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 3df2c4 in the box below so that we can be sure you are a human.