FreeKB - Java class - Getting Started
Java class - Getting Started

Home > Search


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 use certain objects, the class that contains the objects will be used.

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

 

In this example, the MyClass.java class is in the com.sample.main package. There is a public class called "MyClass", a public method called "myMethod", and a variable called "name" with a value of "John Doe".  The "name" variable is returned, so that it can be used (such as in a JSP page).

package com.sample.main;

public class MyClass {
  public String myMethod() {
    final String name = "John Doe";
    return name;
  }
}

 

This variation produces the same exact result. This would make the "name" variable is accessible in more than one method.

package com.sample.main;

public class MyClass {
  public String name = "John Doe";

  public String myMethod(){
    return name;
  }

  public String myOtherMethod(){
    return name;
  }

}

 

This variation, which uses a constructor to update the name variable to have a value of John Doe, produces the same exact result.

package com.sample.main;

public class MyClass {
  public String name;

  // constructor
  public MyClass() {
    name = "John Doe";
  }

  // method
  public String myMethod(){
    return name;
  }

}

 

The class be imported into a JSP page.

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments