class / new / Constructor / this
This is the basic syntax for defining a class and creating an instance. Use class to define a class and new to create an instance. A constructor is a special method that is called automatically when an instance is created.
Syntax
// Define a class.
class ClassName {
// Field (instance variable)
type fieldName;
// Constructor (same name as the class, no return type)
ClassName(parameter) {
this.fieldName = parameter;
}
// Method
returnType methodName(parameter) {
// Process
}
}
// Create an instance.
ClassName obj = new ClassName(argument);
// Access a method or field.
obj.methodName();
obj.fieldName;
// this keyword: calls another constructor in the same class.
this(argument);
Keywords and Syntax
| Keyword | Description |
|---|---|
| class | Defines a class — a blueprint that groups fields, constructors, and methods. |
| new | Creates an instance (object) of a class on the heap memory. |
| Constructor | A special method with the same name as the class and no return type. It is called automatically when new is used. |
| this | Refers to the current instance. Use this.fieldName to distinguish a field from a parameter with the same name. |
| this(argument) | Calls another constructor in the same class. Must be placed on the first line of the constructor. |
Sample Code
// Define the Person class.
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name; // Use this to distinguish the field from the parameter.
this.age = age;
}
// Delegating constructor (calls another constructor using this)
Person(String name) {
this(name, 0); // Calls Person(String, int).
}
// Method
String greet() {
return "Hello, I'm " + this.name + ".";
}
}
// Create an instance and call a method.
Person alice = new Person("Alice", 30);
System.out.println(alice.greet()); // Prints "Hello, I'm Alice."
System.out.println(alice.age); // Prints "30"
Person bob = new Person("Bob");
System.out.println(bob.age); // Prints "0"
// Each instance has its own independent fields.
Person carol = new Person("Carol", 25);
System.out.println(carol.name); // Prints "Carol"
Overview
A Java class consists of fields, constructors, and methods. A constructor has no return type and is defined with the same name as the class. If you do not define a constructor, the compiler automatically generates a no-argument default constructor. However, if you define a constructor with parameters, the default constructor is not generated automatically.
The this keyword is used to distinguish between a field name and a parameter name when they are the same, and to chain constructors together. this(argument) can only be written on the first line of a constructor.
For access modifiers (public / private, etc.), see public / private / protected / static / final. For inheritance, see extends / super / @Override.
If you find any errors or copyright issues, please contact us.