This introduction/refresher to Java Classes is assuming that you’ve worked with some Object Oriented language before, like C++, or maybe even Java and you just need a quick refresher.
In Java, everything you build will be a class, with very few exceptions. to define a class, you will need a file name, with the same name as your class.
Inside the file, you will specify who has permissions to access your class, not the methods and variables inside the class, just the class itself, the class keyword, so it knows you’re defining a class, and the class name. Then you will have your braces to contain the body of your class.
Consider this class, and extension of the previous example we looked at.
public class Greeting {
}
Notice that the class name starts with a capital letter. While not strictly required, it is good practice and common parlance. We also specify that this is a publicly accessible class.
Inside this class, we will put class methods and variables. Some of the methods might be used for getting and setting a object variable.
Anything inside those braces belong to the class. So we can put class level variables, which are accessible to the whole class and methods inside the class definition.
public class Greeting {
private int location;
private String message;
}
Notice when we create class level variables, we don’t assign them a value. This should be done in a constructor. A constructor is a special method which gets called whenever an object is “constructed” or created. A constructor call is created each time an object is created. So if you have three (3) objects of the same class, the constructor is called three times, one for each object.
public class Greeting {
private int location;
private String message;
public Greeting() {
this.location = 3;
this.message = "Welcome to Earth.";
}
}
Notice inside the constructor we set the class level variables. Here are a few other things to notice about the Java Constructor.
Notice that a constructor doesn’t have a return type. It returns the type of the class, as it is creating an object, but no return type is shown.
A constructor method is designated by the same name as the class. This includes the capitalization.
The accessor modifier is normally public. This isn’t required however, especially for inner classes which we’ll look at later.
Inside a method, or constructor, you will generally use the this. notation to reference a class level variable. This is to limit confusion between local variables and class level variables. (It isn’t required, but if you don’t use it, and you have a local variable with the same name, the local variable gets used instead of the class level variable.)
Intro to Java Classes was originally found on Access 2 Learn