Topics Covered

The following topics will be covered on this section:

  • How to declare a class
  • How to declare a class variable
  • How to define a class constructor
  • How to call a class constructor
  • How to define a class method
  • How to use class method
  • Class Access Control
  • Method Access control
  • How to create a java object

Class Declaration

From our previous tutorial we have shown already on how to declare a class. Basically a class is declared as below:

public class ClassName {
	// variable declaration
	// method declaration
}

The keyword public from the above declaration is what we call access control. There are 4 possible access control that we can use:

  • public – the class when declared public will be accessible on all classes that import the package
  • protected – the class is accessible to all class on the same package and its subclass
  • no modifier – class is accessible to all class on the same package
  • private – you might not want to declare your class private not unless the class is an inner class because if you declare your class as private, it will not be accessible at all. This is helpful if the inner class implementation is only intended on  the parent class to be used.

After the keyword public we have implicitly call another keyword which is class. This is a reserved word which is intended only in declaring a class. After the class keyword, the class name to identity the class should come. There is general convention accepted by Java Community in naming a class, start with uppercase letter. By convention we mean that the code will still compile and run without following it but will make it unreadable. After the class name declaration, the class body comes next. Anything inside the opening and close bracket are called class body. This where the code implementation comes in.
The class body can consists variable declaration and method declaration. These member variables are the one that perform the actual implementation of the class.

Now that we have discussed the basic of a class, let’s tackle more on a advance class declaration.

public class ClassName extends AnotherClass implements MyInterface {
	// variable declaration
	// method declaration
}

There are two additional keyword we have added from the basic class declaration which are the following:

  • extends
  • implements

The extends keyword means that ClassName is a subclass of AnotherClass which means to say that the class ClassName inherits all the behavior of the parent class AnotherClass. As a general rule, a class can only have one parent class.

Meanwhile the implements keyword means that ClassName class implements the interface MyInterface. Basically an interface is like a blue print of a class, it doesn’t have any concrete implementation. It’s only sole purpose in life is to be implemented. A class can implement multiple interfaces. So if we want to add another interface on our class we just declare it after the keyword implements and separate the interfaces by comma.

public class ClassName extends AnotherClass implements MyInterface,AnotherInterface {
	// variable declaration
	// method declaration
}

Make a note that once we make use of the implement  keyword, we forced our class to provide a concrete implementation of all the methods that the interface provides.

Class Variable Declaration

Basically a class variable are those variables that is accessible on the entire class. Depending on the access modifier these variables can also be access outside the class.

public class DeskFan {
	private boolean powerOn = false;
	public int currentGearSpeed = 3;
	protected boolean isOscillating = true;
	static public int voltage = 220;

	void turnOn(boolean newVal) {
		powerOn = newVal;
	}	
}

 

From the above  example code snippet of the class DeskFan, we have declared quite a few variables which is the powerOn, currentGearSpeed, isOscillating and voltage. Please go over on our tutorial on the variable declaration to learn the naming convention in declaring a variable if you still not familiar with it.

There are two data types we have used from the above example:

  • int data type – for variable currentGearSpeed and voltage
  • boolean data type – for variable powerOn and isOscillating

As we have pointed already that there is a convention in naming a variable which is using camel case. You can choose to ignore it however it is highly discourage.

Notice the keywords public, private and protected before the data type declaration. Similar to class, variables has access modifiers too. So even we can declare the class as public we can still limit the visibility of the variables by using access modifiers. Why we have to go into trouble to do that? When coding a class, we might be using a lot of variables and method declaration. Exposing all of these variables would not make any sense at all. Let’s say we want to design a class that accepts a employee id variable and this class provides methods and variables that return all the employee information. Let’s say we have another class that calls this class that we have to get the employee information, it would not make sense for the calling class to see variables regarding database connections, or maybe data formatting. So basically what we gonna do is to make only those methods that gives detailed employee information as public and we hide the rest of the methods and variables by declaring it as private.

Method Declaration

On this section we will be showing on how to declare a class method. Let’s create a simple method.

	protected Integer calculateArea(int width, int length){
		int areaTriangle = width * length;
		return areaTriangle;
	}

 

Similar to class declaration and variable declaration, a method has access modifiers too. Why we have to consider the access modifiers? The same rationale as what we have given on variable declaration, this is necessary to hide the methods that we don’t want to exposed. So from the above example, we have used protected as we don’t want to exposed this method outside our package. After declaring the method as protected, we have put the return type which is in this case an Integer object. Depending on the desired implementation, we can put any object type as return object. Moving back to the example, we used Integer object type thus the calculateArea method returns an Integer value to whatever calls this method. This declaration forcefully make our method to absolutely return a value thus a keyword return on the end part of our method body. If you don’t want your method not to return any value, just put void as return type.

So far we have discussed the protected and Integer keywords on our method declaration. What comes next after the return type is the calculateArea. This is the method name which we will be using to call this code block whenever needed. So what are those variables after method name  calculateArea(int width, int length) ?  Basically the width and length are called method arguments. Any method can have zero method argument or can have multiple arguments. To declare a method argument, specify first the variable type and then proceed with the variable name. If you have multiple argument, separate those with comma.

Method Overloading

One of the most advance topic in handling java methods is the concept of method overloading. The idea behind this is to reuse existing method name to accommodate additional method parameters. Let’s say for example we have a class that handles calculation of areas of polygons and with that functionality we have declared a method calculateArea. Under normal circumstances we would be creating different method name to handle calculation of area of a triangle, area of rectangle, etc. What if we want to use the calculateArea method name since it is very intuitive? This can be solved using method overloading. What we gonna do is to create the same method name but with different method signature.

package com.javatutorial.example;

public class PolygonUtilities {
	
	
	public double calculateArea(double width,double height){
		return width * height;
	}
	public double calculateArea(double width, double height, double multiplier){
		return multiplier * width * height;
	}

}

What I mean when I say that we can create the same method name but with different method signature

Class Constructor

A class constructor is basically can be considered also as a method but a special one. The method name is the same as the class name.

package com.javatutorial.example;

public class Employee {
	
	String fullName;
	String firstName;
	String lastName;
	int age;
	
	
	public Employee(String firstName,String lastName){
		this.fullName = firstName + " " + lastName;
		this.firstName = firstName;
		this.lastName= lastName;
	}	


}

 

There are a lot of things from the above example. Let’s take it one by one. There are four class variables declared which is the fullName, firstName, lastName, and age. And after the variable declaration here comes the constructor. As discussed already when we declare a constructor, it must match the name of the class. In this case, we have declared two constructor parameter which is firstName and lastName. I hope you have noticed that there are two declaration of firstName and lastName variables. One place is on the class declaration and another one is declared as method argument. Let’s say we have to assign the value that comes from the constructor to the one that is declared as class variable? We cannot do firstName = firstName right? It wouldn’t make sense at all. To handle this scenario, we can use the keyword this appended with . and then the variable name.

On later chapter we would be discussing more on the use of “.” as this is somewhat special.

Similar to method, a class constructor can also be overloaded. Let’s rewrite the Employee class and let’s overload the existing constructor with additional method argument age.

package com.javatutorial.example;

public class Employee {
	
	String fullName;
	String firstName;
	String lastName;
	int age;
	
	
	public Employee(String firstName,String lastName){
		this.fullName = firstName + " " + lastName;
		this.firstName = firstName;
		this.lastName= lastName;
	}
	
	public Employee(String firstName,String lastName, int age){
		this(firstName,lastName);
		this.age = age;
	}

}

The two constructor declared on the Employee class looks exactly the same it such that the second constructor has 3rd argument which is age. As the implementation would be the same also for setting up the firstName, lastName and fullName, we don’t have to have a separate implementation rather we can leverage the existing constructor. To use the existing constructor, just call use the keyword this. Sounds good right? This is a good design and best practice in such cases where the different constructors share same implementation. This design is eminent also on the existing Java API where multiple constructors are in place.

Java Object Creation

From previous part of this tutorial we have tackled all about classes. Basically a java class is a blue print of an object. An object is created by instantiating a class. Below are sample creation of java object:

Employee emp = new Employee("ryan", "salvador",32);
String str = new String("abcd1234");
Integer number = new Integer(1234);

There are three objects created from the above snipped; emp,str and number. The syntax in creating an object is <Object Type> <object name> = new <Object constructor>.

Let’s take into consideration the code on line 1. Basically it means that an Employee object with emp as its name is instantiated using the class constructor of Employee class that accepts 3 argument which is firstName, lastName and age. The firstName is set as ryan, lastName is salvador and age is 32. This constructor is basically pattern from previous sections in declaring class constructors of employee class. Basically in instantiating an object we used the keyword new.

The second and third declaration are for creation of String and Integer object. These classes are part of the Java API and we can use it anytime as we see fit. Make a mastery of in instantiating a java object because Java is all about objects and in order to use the java API available, we must instantiate them first.

Now that we know how to create a java object, now how can we use them? Let’s use our previous examples to illustrate this.

package com.javatutorial.example;

public class Employee {
	
	String fullName;
	String firstName;
	String lastName;
	int age;
	
	
	public Employee(String firstName,String lastName){
		this.fullName = firstName + " " + lastName;
		this.firstName = firstName;
		this.lastName= lastName;
	}
	
	public Employee(String firstName,String lastName, int age){
		this(firstName,lastName);
		this.age = age;
	}

}

The class constructors of the employee class is overloaded, one is accepting two string argument while the other is accepting three. Let’s create an Employee object from this class and instantiate it with firstName as “ryan”, lastName as “salvador” and age as “32”.

 

Create a class Main and then instantiate a new Employee object. Name the new Employee object as emp and initialize it by calling one of the Employee constructors. I have prepared the demonstration above on how to create an Employee object and how to instantiate it. If you look at the constructors of the employee class, the fullName variable is exposed and can be called anytime. But where the value of the fullName will come from. Basically the fullName comes from the constructors of the Employee class. It is implemented as such that it combines firstName + ” ” + lastName. So whenever we initialize the Employee class and use any of it’s constructors, the fullName is also assigned to certain value depending on the value passed on the constructor.

We pretty much covered everything about classes, object, method and constructor. We are pretty much almost at the middle of Core Java Concepts. Please head out to the next article to finish your learning of java programming.