The Concept of Java Classes and Objects
The Concept of Java Classes and Objects
Classes and objects are the two most essential Java concepts that every
programmer must learn. Classes and objects are closely related and work together.
An object has behaviors and states, and is an instance of class. For instance, a cat
is an object—it’s color and size are states, and its meowing and clawing furniture are
behaviors. A class models the object, a blueprint or template that describes the state
or behavior supported by objects of that type.
What Is a Class?
We can define a class as a container that stores the data members and methods together.
These data members and methods are common to all the objects present in a particular
package.
Every class we use in Java consists of the following components, as described below:
Access Modifier
Object-oriented programming languages like Java provide the programmers with four types
of access modifiers.
Public
Private
Protected
Default
These access modifiers specify the accessibility and users permissions of the methods and
members of the class.
Class Name
This describes the name given to the class that the programmer decides on, according to the
predefined naming conventions.
The body of the class mainly includes executable statements. Apart from these, a class may
include keywords like "super" if you use a superclass, "implements" if you are inheriting
members, methods, and instances from the same class, and "interface" if you are inheriting
any members, methods, and instances from a different class.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
Type of Classes
Built-in classes are just the predefined classes that come along with the Java Development
Kit (JDK). We also call these built-in classes libraries. Some examples of built-in classes
include:
java.lang.System
java.util.Date
java.util.ArrayList
java.lang.Thread
User-Defined Classes
User-defined classes are rather self-explanatory. The name says it all. They are classes that
the user defines and manipulates in the real-time programming environment. User-defined
classes are broken down into three types:
Concrete Class
Concrete class is just another standard class that the user defines and stores the methods and
data members in.
Syntax:
class con{
//class body;
Abstract Class
Abstract classes are similar to concrete classes, except that you need to define them using the
"abstract" keyword. If you wish to instantiate an abstract class, then it should include an
abstract method in it. Otherwise, it can only be inherited.
Syntax:
//method();
Interfaces
Interfaces are similar to classes. The difference is that while class describes an object’s
attitudes and behaviors, interfaces contain the behaviors a class implements. These interfaces
will only include the signatures of the method but not the actual method.
Syntax:
The following rules are mandatory when you're working with Java classes:
Every class name should start with an upper case character, and if you intend to
include multiple words in a class name, make sure you use the camel case
A Java project can contain any number of default classes but should not hold
more than one public class
You can implement multiple interfaces by writing their names in front of the class,
separated by commas
You should expect a Java class to inherit only one parent class
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:
Main.java
Create a class named "Main" with a variable x:
int x = 5;
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:
int x = 5;
System.out.println(myObj.x);
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
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
Main.java
public class Main {
int x = 5;
Second.java
class Second {
System.out.println(myObj.x);
5
What are Java Objects?
An object is a variable of the type class, it is a basic component of an
object-oriented programming system. A class has the methods and data
members (attributes), these methods and data members are accessed
through an object. Thus, an object is an instance of a class.
If we consider the real world, we can find many objects around us, cars,
dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, and color, and the
behavior is - barking, wagging the tail, and running.
If you compare the software object with a real-world object, they have
very similar characteristics. Software objects also have a state and a
behavior. A software object's state is stored in fields and behavior is
shown via methods. So, in software development, methods operate on
the internal state of an object, and the object-to-object communication is
done via methods.
int x = 5;
int y = 3;
Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):
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:
Example
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
}
}
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
int x;
myObj.x = 40;
System.out.println(myObj.x);
Example
Change the value of x to 25:
int x = 10;
System.out.println(myObj.x);
If you don't want the ability to override existing values, declare the attribute
as final:
Example
public class Main {
System.out.println(myObj.x);
The class methods are declared by specifying the access modifier followed by
the return type, method_name, and parameters list.
Syntax
Use the below syntax to declare a Java class method:
Example
Here is the source code of the above defined method called minimum().
This method takes two parameters n1 and n2 and returns the minimum
between the two −
class Util {
/** the snippet returns the minimum between two numbers */
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Accessing Java Class Methods
To access a class method (public class method), you need to create an
object first, then by using the object you can access the class method
(with the help of dot (.) operator).
Syntax
Use the below syntax to access a Java public class method:
object_name.method_name([parameters]);
Example
Following is the example to demonstrate how to define class method and
how to access it. Here, We've created an object of Util class and call
its minimum() method to get minimum value of given two numbers
Example
Following is the example to demonstrate how to define class method and how to access it.
Here, We've created an object of Util class and call its minimum() method to get minimum
value of given two numbers −
class Util {
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
public class Tester {
Output
Minimum value = 6
You learned from the Java Methods chapter that methods are declared within
a class, and that they are used to perform certain actions:
System.out.println("Hello World!");
Example
Inside main, call myMethod():
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
In the example above, we created a static method, which means that it can
be accessed without creating an object of the class, unlike public, which can
only be accessed by objects:
Example
An example to demonstrate the differences
between static and public methods:
// Static method
// Public method
// Main method
Note: You will learn more about these keywords (called modifiers) in
the Java Modifiers chapter.
Example explained
1) We created a custom Main class with the class keyword.
3) The fullThrottle() method and the speed() method will print out some
text, when they are called.
5) In order to use the Main class and its methods, we need to create
an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
Remember that..
The dot (.) is used to access the object's attributes and methods.
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:
Main.java
Second.java
Main.java
public class Main {
Second.java
class Second {
Output
If we compile and run the above program, then it will produce the
following result −
Example 2
Following is the EmployeeTest class, which creates two instances of the
class Employee and invokes the methods for each object to assign values
for each variable.
Save the following code in EmployeeTest.java file.
import java.io.*;
public class EmployeeTest {
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Output
Now, compile both the classes and then run EmployeeTest to see the
result as follows −
Class:
The computer does not allocate memory when you declare a class
Objects:
You can create any number of objects using one single class
A class attribute defines the state of the class during program execution.
A class attribute is accessible within class methods by default.
For example, there is a class "Student" with some data members
(variables) like roll_no, age, and name. These data members are considered
class attributes.
Syntax
Use the below syntax to declare a class attribute:
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
In above class, we've fields like breed, age, and color which are also
known as class attributes.
Syntax
Use the below syntax to access a class attribute:
object_name.attribute_name;
class Dog {
// Declaring and initializing the attributes
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}
Output
German Shepherd
2
Black
Differentiate the instance variables from local variables if they have same names,
within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
Call one type of constructor (parametrized constructor or default) from other in a
class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Tester() {
System.out.println("This is an example program on keyword this");
}
Tester(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable num
this.num = num;
}
Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
Example
The following example demonstrates the difference between public and static class methods:
Output
For example, you might use finalize( ) to make sure that an open file
owned by that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The
Java runtime calls that method whenever it is about to recycle an object
of that class.
Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.
This means that you cannot know when or even if finalize( ) will be
executed. For example, if your program ends before garbage collection
occurs, finalize( ) will not execute.
Java Constructors
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit
return type.
Typically, you will use a constructor to give initial values to the
instance variables defined by the class or to perform any other start-up
procedures required to create a fully formed object.
All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your constructor, the default
constructor is no longer used.
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void
as a return type.
There can be multiple constructors in the same class, this concept is
known as constructor overloading.
The access modifiers can be used with the constructors, use if you
want to change the visibility/accessibility of constructors.
Java provides a default constructor that is invoked during the time
of object creation. If you create any type of constructor, the default
constructor (provided by Java) is not invoked.
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Default Constructor
No-Args Constructor
Parameterized Constructor
1. Default Constructor
If you do not create any constructor in the class, Java provides a default
constructor that initializes the object.
Output
num1 : 0
num2 : 0
Output
num1 : -1
num2 : -1
3. Parameterized Constructor
A constructor with one or more arguments is called a parameterized
constructor.
Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way that
they are added to a method, just declare them inside the parentheses
after the constructor's name.
System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
}
Output
obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200
// A simple constructor.
class MyClass {
int x;
Output
10 20
// no-args constructor
Student() {
this.name = "Unknown";
this.age = 0;
}
// Printing details
System.out.println("std1...");
std1.printDetails();
System.out.println("std2...");
std2.printDetails();
System.out.println("std3...");
std3.printDetails();
}
}
Output
td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25
Java access modifiers are used to specify the scope of the variables, data
members, methods, classes, or constructors. These help to restrict and
secure the access (or, level of access) of the data.
There are four different types of access modifiers in Java, we have listed
them as follows:
boolean processOrder() {
return true;
}
Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if
public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates
itself and hides data from the outside world.
Example 1
The following class uses private access control −
So, to make this variable available to the outside world, we defined two
public methods: getFormat(), which returns the value of format,
and setFormat(String), which sets its value.
Example 2
In this example, the data members and class methods of the Logger class
are private. We are trying to access those class methods in another
class Main.
class Logger {
private String format;
}
}
Output
Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
Example 1
The following parent class uses protected access control, to allow its child
class override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Example 1
This example demonstrates the use of protected access modifier.
// Class One
class One {
protected void printOne() {
System.out.println("printOne method of One class.");
}
}
Output
Syntax
The following function uses public access control −
// Class One
class One {
public void printOne() {
System.out.println("printOne method of One class.");
}
}
Output
public Puppy() {
}
Output
Java access modifiers are used to specify the scope of the variables, data members, methods,
classes, or constructors. These help to restrict and secure the access (or, level of access) of the
data.
There are four different types of access modifiers in Java, we have listed them as follows:
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
boolean processOrder() {
return true;
}
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class, if public getter methods
are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.
Example 1
The following class uses private access control −
Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String), which sets
its value.
Example 2
In this example, the data members and class methods of the Logger class are private. We are
trying to access those class methods in another class Main.
class Logger {
private String format;
}
}
Output
The protected access modifier cannot be applied to class and interfaces. Methods, fields can
be declared protected, however methods and fields in a interface cannot be declared
protected.
Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
Example 1
The following parent class uses protected access control, to allow its child class
override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be accessible from any
other class other than AudioPlayer. If we define it as public, then it would become accessible
to all the outside world. But our intention is to expose this method to its subclass only, that's
why we have used protected modifier.
Example 1
This example demonstrates the use of protected access modifier.
// Class One
class One {
protected void printOne() {
System.out.println("printOne method of One class.");
}
}
Output
However, if the public class we are trying to access is in a different package, then the public
class still needs to be imported. Because of class inheritance, all public methods and variables
of a class are inherited by its subclasses.
Syntax
The following function uses public access control −
// Class One
class One {
public void printOne() {
System.out.println("printOne method of One class.");
}
}
Output
The following table shows the summary of the accessibility in the same/different classes (or,
packages) based on the access modifiers.
Example of Access Modifiers with Inheritance
In this example, we've created a class with a private variable age and a variable with default
scope as name. Using setter/getter method, we're updating age and getting value and name is
updated directly.
public Puppy() {
}
Output
Age: 2, name: Tommy
Print Page