Java Class Objects
Java Class Objects
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place
them at a single place and reuse them instead of repeating it.
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
1
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and methods
from the class.
You will learn much more about classes and objects in the next chapter.
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.
Create a Class
To create a class, use the keyword class.
[Link]
public class Main {
int x = 5;
}
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
2
In Java, an object is created from a class. After defining a class, you can create objects
from it using the new keyword:
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
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:
[Link]
[Link]
[Link]
public class Main {
3
int x = 5;
}
[Link]
class Second {
public static void main(String[] args) {
Main myObj = new Main();
[Link](myObj.x);
}
}
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot
syntax (.):
4
The following example will create an object of the Main class, with the name myObj.
We use the x attribute on the object to print its value:
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
public class Main {
int x;
Example
Change the value of x to 25:
public class Main {
int x = 10;
5
If you don't want the ability to override existing values, declare the attribute
as final:
Example
public class Main {
final int x = 10;
The final keyword is called a "modifier". You will learn more about these in the Java
Modifiers Chapter.
Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one
object, without affecting the attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
[Link](myObj1.x); // Outputs 5
[Link](myObj2.x); // Outputs 25
}
}
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
6
int age = 24;
myMethod()prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;
7
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:
// Create a Main class
public class Main {
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:
[Link]
[Link]
[Link]
[Link]
public class Main {
public void fullThrottle() {
[Link]("The car is going as fast as it can!");
}
Instructions
Inside the Main class, complete the following steps:
1. Create a String variable named city and set it to "London"
2. Create an int variable named population and set it to 9000000
3. Inside main(), create an object of Main named myObj
4. Print city and population using myObj
9
public class Main {
// Create a String variable
// Create an int variable
public static void main(String[] args) {
// Create a Main object
// Print city the object
// Print population using the object
}
}
Java Constructors
Java Constructors
A constructor in Java is a special method that is used to initialize objects.
public Main() {
// Outputs 5
Note that the constructor name must match the class name, and it cannot have
a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial values
for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a parameter to
the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
}
// Outputs 5
11
You can have as many parameters as you want:
Example
public class Main {
int modelYear;
String modelName;
Java this
Java this Keyword
The this keyword in Java refers to the current object in a method or constructor.
The this keyword is often used to avoid confusion when class attributes have the
same name as method or constructor parameters.
To refer to the class variable and not the parameter, you can use the this keyword:
12
}
Without this, the code above x = x; would set the parameter x equal to itself, and
the class variable would stay uninitialized (0).
This is useful when you want to provide default values or reuse initialization code
instead of repeating it.
Example
public class Main {
int modelYear;
String modelName;
[Link]();
[Link]();
}
}
Output:
2020 Corvette
1969 Mustang
Note: The call to this() must be the first statement inside the constructor.
Java Modifiers
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of
our examples:
The public keyword is an access modifier, meaning that it is used to set the access
level for classes, attributes, methods and constructors.
Access Modifiers
For classes, you can use either public or default:
14
default The class is only accessible by classes in the same package.
This is used when you don't specify a modifier. You will learn
more about packages in the Packages chapter
For attributes, methods and constructors, you can use the one of the following:
default The code is only accessible in the same package. This is used
when you don't specify a modifier. You will learn more about
packages in the Packages chapter
protected The code is accessible in the same package and subclasses. You
will learn more about subclasses and superclasses in
the Inheritance chapter
Non-Access Modifiers
Non-access modifiers do not control visibility (like public or private), but instead
add other features to classes, methods, and attributes.
The most commonly used non-access modifiers are final, static, and abstract.
Final
If you don't want the ability to override existing attribute values, declare attributes
as final:
[Link](myObj.x);
Static
A static method belongs to the class, not to any specific object. This means you
can call it without creating an object of the class.
Example
A simple example showing how to call a static method directly:
// Static method
// Main method
17
Note: A static method belongs to the class itself. You can call it without creating
an object, but it cannot use variables or methods that belong to an object.
REMOVE ADS
Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:
[Link]
[Link]
// abstract class
abstract class Main {
18
Non-Access Modifiers List
For classes, you can use either final or abstract:
final The class cannot be inherited by other classes (You will learn more about
inheritance in the Inheritance chapter)
abstract The class cannot be used to create objects (To access an abstract class, it must
be inherited from another class. You will learn more about inheritance and
abstraction in the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:
Modifier Description
static Attributes and methods belong to the class, not to objects. This means all objects
share the same static attribute, and static methods can be called without
creating objects.
abstract Can only be used in an abstract class, and can only be used on methods. The
method does not have a body, for example abstract void run();. The body
is provided by the subclass (inherited from). You will learn more about inheritance
and abstraction in the Inheritance and Abstraction chapters
19
transient Attributes and methods are skipped when serializing the object containing them
volatile The value of an attribute is not cached thread-locally, and is always read from the
"main memory"
Java Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users. To achieve this, you must:
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:
// Getter
return name;
// Setter
[Link] = newName;
Example explained
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
Example
public class Main {
[Link]([Link]); // error
21
}
If the variable was declared as public, we would expect the following output:
John
Instead, we use the getName() and setName() methods to access and update the
variable:
Example
public class Main {
[Link]([Link]());
// Outputs "John"
REMOVE ADS
22
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method),
or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting
other parts
Increased security of data
Java Packages
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and
much much more. The complete list can be found at Oracles
website: [Link]
The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain
all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to
get user input, write the following code:
Example
import [Link];
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import [Link];
class Main {
[Link]("Enter username");
24
REMOVE ADS
Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the [Link] package. This package also contains date and
time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the [Link] package:
Example
import [Link].*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:
Example
└── root
└── mypack
└── [Link]
[Link]
package mypack;
class MyPackageClass {
[Link]("This is my package!");
}
25
}
The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package within
the same directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class
names.
When we compiled the package in the example above, a new folder was created,
called "mypack".
This is my package!
Java Inheritance
26
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):
[Link]("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar
object
[Link]();
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited
methods to perform different tasks.
REMOVE ADS
...
...
Java Polymorphism
28
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that
are related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform
different tasks. This allows us to perform a single action in different ways.
}
29
Remember from the Inheritance chapter that we use the extends keyword to inherit
from a class.
Now we can create Pig and Dog objects and call the animalSound() method on
both of them:
Example
class Animal {
class Main {
30
Animal myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
[Link]();
Java super
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
31
public void animalSound() {
[Link]();
Output:
Note: Use super when you want to call a method from the parent class that has
been overridden in the child class.
32
Example
class Animal {
[Link]();
Output:
Animal
Example
33
class Animal {
Animal() {
[Link]("Animal is created");
Dog() {
[Link]("Dog is created");
Output:
Animal is created
Dog is created
Note: The call to super() must be the first statement in the subclass constructor.
34
Java Inner Classes
In Java, it is also possible to nest classes (a class within a class). The purpose of
nested classes is to group classes that belong together, which makes your code more
readable and maintainable.
To access the inner class, create an object of the outer class, and then create an
object of the inner class:
int x = 10;
class InnerClass {
int y = 5;
[Link](myInner.y + myOuter.x);
// Outputs 15 (5 + 10)
35
Private Inner Class
Unlike a "regular" class, an inner class can be private or protected. If you don't want
outside objects to access the inner class, declare the class as private:
Example
class OuterClass {
int x = 10;
int y = 5;
[Link](myInner.y + myOuter.x);
If you try to access a private inner class from an outside class, an error occurs:
[Link]: error: [Link] has private access in OuterClass
[Link] myInner = [Link] InnerClass();
^
REMOVE ADS
36
Static Inner Class
An inner class can also be static, which means that you can access it without
creating an object of the outer class:
Example
class OuterClass {
int x = 10;
int y = 5;
[Link](myInner.y);
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have
access to members of the outer class.
Example
class OuterClass {
int x = 10;
class InnerClass {
return x;
[Link]([Link]());
// Outputs 10
Java Abstraction
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have
a body. The body is provided by the subclass (inherited from).
[Link]("Zzz");
From the example above, it is not possible to create an object of the Animal class:
To access the abstract class, it must be inherited from another class. Let's convert the
Animal class we used in the Polymorphism chapter to an abstract class:
Remember from the Inheritance chapter that we use the extends keyword to inherit
from a class.
39
abstract class Animal {
// Regular method
[Link]("Zzz");
class Main {
[Link]();
[Link]();
40
Why And When To Use Abstract Classes and Methods?
To achieve security - hide certain details and only show the important details of an
object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more
about in the next chapter.
Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
interface Animal {
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends). The
body of the interface method is provided by the "implement" class:
Example
// Interface
interface Animal {
41
public void animalSound(); // interface method (does not have a
body)
[Link]("Zzz");
class Main {
[Link]();
[Link]();
Notes on Interfaces:
42
Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement"
class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces, separate
them with a comma (see example below).
REMOVE ADS
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
interface SecondInterface {
43
class DemoClass implements FirstInterface, SecondInterface {
[Link]("Some text..");
class Main {
[Link]();
[Link]();
Anonymous Class
An anonymous class is a class without a name. It is created and used at the same
time.
Here, we create an anonymous class that extends another class and overrides its
method:
44
// Normal class
class Animal {
[Link]("Animal sound");
[Link]("Woof woof");
[Link]();
Woof woof
// Interface
45
interface Greeting {
void sayHello();
[Link]("Hello, World!");
};
[Link]();
Hello, World!
Java Enums
46
Enums
An enum is a special "class" that represents a group of constants (unchangeable
variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate
the constants with a comma. Note that they should be in uppercase letters:
LOW,
MEDIUM,
HIGH
Example
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
47
public static void main(String[] args) {
[Link](myVar);
MEDIUM
Example
enum Level {
LOW,
MEDIUM,
HIGH
switch(myVar) {
case LOW:
[Link]("Low level");
break;
48
case MEDIUM:
[Link]("Medium level");
break;
case HIGH:
[Link]("High level");
break;
Medium level
Example
for (Level myVar : [Link]()) {
[Link](myVar);
An enum cannot be used to create objects, and it cannot extend other classes (but it
can implement interfaces).
49
Why And When To Use Enums?
Use enums when you have values that you know aren't going to change, like month
days, days, colors, deck of cards, etc.
Enum Constructor
An enum can also have a constructor just like a class.
The constructor is called automatically when the constants are created. You cannot
call it yourself.
Here, each constant in the enum has a value (a string) that is set through the
constructor:
enum Level {
LOW("Low level"),
MEDIUM("Medium level"),
HIGH("High level");
[Link] = description;
50
// Getter method to read the description
return description;
Note: The constructor for an enum must be private. If you don't write private, Java
adds it automatically.
51
Java User Input (Scanner)
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings:
class Main {
[Link]("Enter username");
If you don't know what a package is, read our Java Packages Tutorial.
52
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:
Method Description
In the example below, we use different methods to read data of various types:
Example
import [Link];
53
class Main {
// String input
// Numerical input
Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like "InputMismatchException").
You can read more about exceptions and how to handle errors in the Exceptions
chapter.
REMOVE ADS
54
Complete Scanner Reference
Tip: For a complete reference of Scanner methods, go to our Java Scanner Reference.
Java Dates
Java does not have a built-in Date class, but we can import the [Link] package
to work with the date and time API. The package includes many date and time
classes. For example:
Class Description
If you don't know what a package is, read our Java Packages Tutorial.
55
ExampleGet your own Java Server
import [Link]; // import the LocalDate class
2026-05-23
Example
import [Link]; // import the LocalTime class
[Link](myObj);
This example displays the server's local time, which may differ from your local time:
56
1:11:36.652986
Example
import [Link]; // import the LocalDateTime class
[Link](myObj);
2026-05-23T01:11:36.652255
Example
import [Link]; // Import the LocalDateTime class
57
public class Main {
The ofPattern() method accepts all sorts of values, if you want to display the date
and time in a different format. For example:
yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"
58
dd-MMM-yyyy "29-Sep-1988"
59