- How do I create a class in Java?
- Java Classes and Objects
- Create a Class
- Main.java
- Create an Object
- Example
- Multiple Objects
- Example
- Using Multiple Classes
- Main.java
- Second.java
- Creating Classes
- Declaring Member Variables
- Controlling who has Access to a Member
- Setting the Type of a Variable
- Naming a Variable
- Classes
How do I create a class in Java?
A class is a specification or blueprint from which individual objects are created. A class contains fields that represent the object’s states and methods that defines the operations that are possible on the objects of the class.
The file name that contains the definition of a class is always the same as the public class name and the extension is .java to identify that the file contains a Java source code.
A class has constructors, a special method that is used to create an instance or object of the class. When no constructor define a default constructor will be used. The constructor method have the same name with the class name without a return value. The constructors can have parameters that will be used to initialize object’s states.
Here is a Person.java file that defines the Person class.
package org.kodejava.example.fundamental; public class Person < private String name; private String title; private String address; /** * Constructor to create Person object */ public Person() < >/** * Constructor with parameter * * @param name */ public Person(String name) < this.name = name; >/** * Method to get the name of person * * @return name */ public String getName() < return name; >/** * Method to set the name of person * * @param name */ public void setName(String name) < this.name = name; >/** * Method to get the title of person * * @return title */ public String getTitle() < return title; >/** * Method to set the title of person * * @param title */ public void setTitle(String title) < this.title = title; >/** * Method to get address of person * * @return address */ public String getAddress() < return address; >/** * Method to set the address of person * * @param address */ public void setAddress(String address) < this.address = address; >/** * Method to get name with title of person * * @return nameTitle */ public String getNameWithTitle() < String nameTitle; if (title != null) < nameTitle = name + ", " + title; >else < nameTitle = name; >return nameTitle; > /** * Method used to print the information of person */ @Override public String toString() < return "Info [" + "name='" + name + ''' + ", title='" + title + ''' + ", address='" + address + ''' + ']'; >>
Here is a ClassExample.java file that defines the ClassExample class that use the Person class.
package org.kodejava.example.fundamental; public class ClassExample < public static void main(String[] args) < Person person = new Person(); person.setName("Andy"); person.setTitle("MBA"); person.setAddress("NY City"); System.out.println(person); String nameTitle1 = person.getNameWithTitle(); System.out.println("Name with title: " + nameTitle1); Person person2 = new Person("Sarah"); String nameTitle2 = person2.getNameWithTitle(); System.out.println("Name with title 2: " + nameTitle2); >>
A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏
Java Classes and Objects
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a «blueprint» for creating objects.
Create a Class
To create a class, use the keyword class :
Main.java
Create a class named » Main » with a variable x:
Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.
Create an Object
In Java, an object is created from a class. We have already created the class named Main , so now we can use this to create objects.
To create an object of Main , specify the class name, followed by the object name, and use the keyword new :
Example
Create an object called » myObj » and print the value of x:
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main :
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:
Main.java
Second.java
When both files have been compiled:
You will learn much more about classes and objects in the next chapters.
Creating Classes
The introduction to object-oriented concepts in the section titled Object, Classes and Interfaces used a Bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes as subclasses. Here is sample code for a possible implementation of a Bicycle class, to give you an overview of a class declaration. Subsequent sections will back up and explain class declarations step by step. For the moment, don’t concern yourself with the details.
public class Bicycle < // the Bicycle class has // three fields public int cadence; public int gear; public int speed; // the Bicycle class has // one constructor public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >// the Bicycle class has // four methods public void setCadence(int newValue) < cadence = newValue; >public void setGear(int newValue) < gear = newValue; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle < // the MountainBike subclass has // one field public int seatHeight; // the MountainBike subclass has // one constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) < super(startCadence, startSpeed, startGear); seatHeight = startHeight; >// the MountainBike subclass has // one method public void setHeight(int newValue) < seatHeight = newValue; >>
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands).
You have seen classes defined in the following way:
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.
The preceding class declaration is a minimal one. It contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,
class MyClass extends MySuperClass implements YourInterface < // field, constructor, and // method declarations >
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private , which determine what other classes can access MyClass , are discussed later in this section. The section on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.
In general, class declarations can include these components, in order:
- Modifiers such as public , private , and a number of others that you will encounter later. (However, note that the private modifier can only be applied to Nested Classes.)
- The class name, with the initial letter capitalized by convention.
- The name of the class’s parent (superclass), if any, preceded by the keyword extends . A class can only extend (subclass) one parent.
- 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.
- The class body, surrounded by braces, <> .
Declaring Member Variables
There are several kinds of variables:
- Member variables in a class—these are called fields.
- Variables in a method or block of code—these are called local variables.
- Variables in method declarations—these are called parameters.
- The Bicycle class uses the following lines of code to define its fields:
public int cadence; public int gear; public int speed;
Field declarations are composed of three components, in order:
- Zero or more modifiers, such as public or private .
- The field’s type.
- The field’s name.
The fields of Bicycle are named cadence , gear , and speed and are all of data type integer ( int ). The public keyword identifies these fields as public members, accessible by any object that can access the class.
Controlling who has Access to a Member
The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private . Other access modifiers will be discussed later.
- public modifier—the field is accessible from all classes.
- private modifier—the field is accessible only within its own class.
In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us:
public class Bicycle < private int cadence; private int gear; private int speed; public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >public int getCadence() < return cadence; >public void setCadence(int newValue) < cadence = newValue; >public int getGear() < return gear; >public void setGear(int newValue) < gear = newValue; >public int getSpeed() < return speed; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>
Setting the Type of a Variable
All variables must have a type. You can use primitive types such as int , float , boolean , etc. Or you can use reference types, such as strings, arrays, or objects.
Naming a Variable
All variables, whether they are fields, local variables, or parameters, follow the same naming rules and conventions that were covered in the Language Basics section, Variables Naming.
In this section, be aware that the same naming rules and conventions are used for method and class names, except that
- the first letter of a class name should be capitalized, and
- the first (or only) word in a method name should be a verb.
Classes
The introduction to object-oriented concepts in the lesson titled Object-oriented Programming Concepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes as subclasses. Here is sample code for a possible implementation of a Bicycle class, to give you an overview of a class declaration. Subsequent sections of this lesson will back up and explain class declarations step by step. For the moment, don’t concern yourself with the details.
public class Bicycle < // the Bicycle class has // three fields public int cadence; public int gear; public int speed; // the Bicycle class has // one constructor public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >// the Bicycle class has // four methods public void setCadence(int newValue) < cadence = newValue; >public void setGear(int newValue) < gear = newValue; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle < // the MountainBike subclass has // one field public int seatHeight; // the MountainBike subclass has // one constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) < super(startCadence, startSpeed, startGear); seatHeight = startHeight; >// the MountainBike subclass has // one method public void setHeight(int newValue) < seatHeight = newValue; >>
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands).