Basic Java

Before we start learning the basic of java, you need to install java platform (JDK 5.0) on your computer to be able to run simple java program. It is available free of charge. Follow the installation instructions, and make sure you set the PATH variable, so you’ll be able to conveniently run the JDK executables ( javac.exe, java.exe ) from any directory, without having to type the full path of the directory where you installed JDK.

Now, after you install and set the PATH, just to make sure it is ready, open command prompt CMD (assume: using Windows), and type:
java -version
It will show the version of installed java on your computer.

Okay, now we will start writing a program.
There are many of Java integrated development environment (IDE) that often being used to develop java program, such as Eclipse, NetBeans, etc. An IDE normally consists of:
          * source code editor
          * compiler
          * build automation tools
          * debugger

But as a start, we can use text editor to write a simple program.
Note: Java programs are case sensitive, so pay attention to the capitalization as you type.

class Employee {
    //declaration of variables
    String name;
    String position;
    Integer salary;
   
    //constructor
    public Employee (String employeeName, String employeePosition, Integer startSalary) {
        name = employeeName;
        position= employeePosition;
        salary= startSalary;
        System.out.println("Class Employee instantiated by new Object name: " + name + ". Position: " + position + ". Salary $: " + salary);
    }
   
    //method
    public String getName() {
        return name;
    }
   
    public String getPosition() {
        return position;
    }
   
    public Integer getSalary() {
        return salary;
    }
   
    public void setName(String newName) {
        name = newName;
    }
   
    public void setPosition(String newPost) {
        position = newPost;
    }
   
    public void setSalary(Integer newSalary) {
        salary = newSalary;
    }
   
    public void requestForLeave() {
        System.out.println("Employee " + name + " requesting for leave.");
    }
   
    public Double receiveOvertime(double overtime_hour) {
        double overtime = overtime_hour / 160d * salary.intValue();
        return overtime;
    }
}

 

Save the text above as Employee.java

To compile from command line, open CMD, go to the directory where you save file Employee.java, then type:
javac Employee.java

This command will compile and create Employee.class

This section defines a class named Employee. As we know, Java is object-oriented, and everything is considered as objects. Class is prototype from which objects are created. In class, we define the state and behavior.

As you noticed, Employee class above does not contain a main method. That’s because it’s not a complete application, just the prototype for employee, and the creation of object Employee can be done in some other class in your application.

For example, we create object employee John, and Jane in class EmployeeDemo below, each having same state like name, position, salary, and the same behavior like requestForLeave(), receiveOvertime(), etc.

class EmployeeDemo {
    public static void main(String[] args){
          Employee John = new Employee("John", "Manager", 7000);
          Employee Jane = new Employee("Jane", "Assistant Manager", 5000);
   
          System.out.println("Employee " + John.getName() + " receive overtime $: " + John.receiveOvertime(8) + " for working overtime 8 hours.");
   
          System.out.println("Employee " + Jane.getName() + " receive overtime $: " + Jane.receiveOvertime(8) + " for working overtime 8 hours.");
   
          John.requestForLeave();
    }
}

 

Save the text above as EmployeeDemo.java
Create EmployeeDemo.class by command: javac EmployeeDemo.java

To run the program, type:
java EmployeeDemo

When the program run, it will execute the main method, and the result is:
Class Employee instantiated by new Object name: John. Position: Manager. Salary $: 7000
Class Employee instantiated by new Object name: Jane. Position: Assistant Manager. Salary $: 5000
Employee John receive overtime $: 350.0 for working overtime 8 hours.
Employee Jane receive overtime $: 250.0 for working overtime 8 hours.
Employee John requesting for leave.

Class Declaration
This is the most minimal syntax for class declaration:

class Employee {
 
}

We can provide more information about the class, the declarations can include these components, in order:
    1. Modifiers such as public, private. If it is not define, by default is public.
    2. The class name, with the initial letter capitalized by convention.
    3. The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
    4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
    5. The class body, surrounded by braces {}.

For example:

public [abstract] class MyClass extends MySuperClass implements YourInterface1, YourInterface2 {
    //variables, constructor, and method declarations
}

MyClass is a subclass of MySuperClass and implements the interface YourInterface1 and YourInterface2.

Variables Declaration

class Employee {
    String name;
    String position;
    Integer salary;
}

Variables declaration are composed of three components, in order:
    1. Access modifiers, such as public or private (Default is public).
            public : the field is accessible from all classes.
            private : the field is accessible only within its own class.
    2. The variable’s type, example: String, Integer.
    3. The variable’s name.

Constructor

class Employee {
    String name;
    String position;
    Integer salary;
   
    //constructor
    public Employee (String argument1, String argument2, Integer argument3) {
        //initiate value from arguments
    }
   
    public Employee (String argument1, String argument2) {
        //initiate value from arguments
    }
   
    //no-argument constructor
    public Employee () {
    }
}

Constructor declarations look like method declarations, except that they use the name of the class and have no return type. Constructor will be invoked to create objects from the class, and directly initiate the value of variables (state) if define. You can write two constructors that have different number and type of arguments. If you do not provide constructor, by default it will call the no-argument constructor of the superclass. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Method Declaration

class Employee {
    public void requestForLeave() {
        System.out.println("Employee " + name + " requesting for leave.");
    }
   
    public Double receiveOvertime(double overtime_hour) {
        double overtime = overtime_hour / 160d * salary.intValue();
        return overtime;
    }
}

Method declarations have general syntax in order:
    1. Modifiers, such as public, private.
    2. The return type : the data type of the value returned by the method, or void if the method does not return a value.
    3. The method name. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc.
    4. The parameter list in parentheses (), with comma-delimited list of input parameters, preceded by their data types. If there are no parameters, you must use empty parentheses.
    5. An exception (throws Exception).
    6. The method body, enclosed between braces {}.

Java Modifier Summary

Modifier Used on Meaning
abstract class
interface
method
Cannot be instantiated, it can only be subclassed.
All interfaces are abstract. Optional in declarations.
No body, only signature. The enclosing class is abstract.
final class
method
field
variable
Cannot be subclassed.
Cannot be overridden and dynamically looked up.
Cannot change its value. static final fields are compile-time constants.
Cannot change its value.
private member Accessible only in its class(which defines it).
protected member Accessible only within its package and its subclasses.
public class
interface
member
Accessible anywhere.
Accessible anywhere.
Accessible anywhere its class is.
static method
field
A class method, invoked through the class name.
A class field, invoked through the class name. One instance, regardless of class instances created.

 

References :

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.