Java Classes and Objects
Java language has object-oriented features to create classes and objects. In this tutorial, we will see how to develop Java classes and instantiate objects from java classes is discussed in detail with examples.
You can also check the Java Classes and Objects Tutorial in the following video:
Table Of Contents
1. Overview
We look at how to define classes and create objects in this article. Nested classes and Enum types in Java are discussed in detail with examples. Java Serialization, Inner classes, Anonymous classes, and Lambda expressions are also presented in this article.
2. Java Classes and Objects Tutorial
2.1 Prerequisites
Java 7 or 8 is required on the linux, windows or mac operating system.
2.2 Download
You can download Java 7 from Oracle site. On the other hand, You can use Java 8. Java 8 can be downloaded from the Oracle web site .
2.3 Setup
You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:
start command
JAVA_HOME=”/desktop/jdk1.8.0_73″ export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
2.4 Java Classes and Objects
2.4.1 Java Classes
Java classes have constructors, member variables and methods. The classes can be at public, private and package levels. Member variables can be public, private and protected. Methods can be at public, private, protected and package levels. You can look at an example class Car
. Car
class has member variables model
, engineType
and vehicleNum
. It has setter and getter methods for accessing and modifying the private member variable values. Here is a Java class example:
Car class
public class Car { public String model; public String engineType; public int vehicleNum; public Car(String model,String engineType,int vehicleNum) { this.model = model; this.engineType = engineType; this.vehicleNum = vehicleNum; } public void setModel(String model) { this.model = model; } public void setEngineType(String engineType) { this.engineType = engineType; } public void setVehicleNum(int vehicleNum) { this.vehicleNum = vehicleNum; } public String getModel() { return this.model; } public String getEngineType() { return this.engineType; } public int getVehicleNum() { return this.vehicleNum; } public void printInfo() { System.out.println("Model " + getModel()); System.out.println("engineType " + getEngineType()); System.out.println("VehicleNum " + getVehicleNum()); } public static void main(String[] args) { Car car = new Car("Toyota Tercel","Single Cylinder",2342334); car.printInfo(); System.out.println("Changing the car properties"); car.setModel("Honda Civic"); car.setEngineType("Four Cylinder"); car.setVehicleNum(45453434); car.printInfo(); } }
The command below executes the above code snippet:
Run Command
javac Car.java java Car
The output of the executed command is shown below.
2.4.2 Encapsulation
In java, data can be encapsulated in a class. The properties of a class are hidden and can only be accessed through setters and getters. Data hiding is shown in the java class example below.
Employee Class
public class Employee { private String name; private String id; private int age; public int getAge() { return age; } public String getName() { return name; } public String getId() { return id; } public void setAge( int age) { this.age = age; } public void setName(String name) { this.name = name; } public void setId( String id) { this.id = id; } }
Encapsulation example shows how to access the properties encapsulated in a class. The implementation is shown below.
Encapsulation Example
public class EncapsulationExample { public static void main(String args[]) { Employee employee = new Employee(); employee.setName("Steve Smith"); employee.setAge(32); employee.setId("243243"); System.out.println("Name : " + employee.getName() + " Age : " + employee.getAge()+ " Id : " + employee.getId()); } }
The command below executes the above code snippet:
Run Command
javac EncapsulationExample.java java EncapsulationExample
The output of the executed command is shown below.
2.4.3 Java Objects
Java objects are created by instantiating a java class. You can create Java objects in the main
method and invoke methods on the objects. The example below shows how different car objects can be created and methods can be invoked.
Object Creator
public class ObjectCreator { public static void main(String[] args) { Car car1 = new Car("Toyota Tercel","Single Cylinder",2342334); Car car2 = new Car("Ford Mustang","DOHC",2394434); car1.printInfo(); car2.printInfo(); System.out.println("Changing the car2 properties"); car2.setModel("Chevorlet Bolt"); car2.setEngineType("Four Cylinder"); car2.setVehicleNum(2234234); car2.printInfo(); } }
The command below executes the above code snippet:
Run Command
javac ObjectCreator.java java ObjectCreator
The output of the executed command is shown below.
2.4.4 Java Inherited Classes
A java class can be subclassed from a parent class. The subclass can use the methods and properties of the parent class. The example below shows the parent class Employee
is implemented.
Employee
public class Employee { private String name; private String id; private int age; public Employee(String name, String id, int age) { this.name = name; this.id = id; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public String getId() { return id; } public void setAge( int age) { this.age = age; } public void setName(String name) { this.name = name; } public void setId( String id) { this.id = id; } }
SalariedEmployee
class is subclassed from Employee
. SalariedEmployee
class has empSalary
property. The implementation of the SalariedEmployee
class is shown below.
SalariedEmployee
public class SalariedEmployee extends Employee { private double empSalary; public SalariedEmployee(String name, String id, int age, double empSalary) { super(name, id, age); setEmpSalary(empSalary); } public double getEmpSalary() { return empSalary; } public void setEmpSalary(double empSalary) { if(empSalary >= 0.0) { this.empSalary = empSalary; } } public static void main(String[] args) { SalariedEmployee salarEmp = new SalariedEmployee("Steve Smith", "Sanjose, CA", 33, 56000.00); Employee emp = new SalariedEmployee("John Ray", "Dallas, TX", 43, 44000.00); System.out.println("Employee "+salarEmp.getName()+" salary " +salarEmp.getEmpSalary()); System.out.println("Employee "+ emp.getName()+ " age "+ emp.getAge()); } }
The command below executes the above code snippet:
Run Command
javac SalariedEmployee.java java SalariedEmployee
The output of the executed command is shown below.
2.4.5 Overriding methods
Instance methods can be overridden by the subclass. The overridden method will have the same signature. A static method can be overridden by the subclass. The difference is in the version of the static method invoked. The version is dependent on the superclass or the subclass. The example shows the overriding static and instance methods. The parent class Vehicle
implementation is shown below in the example.
Vehicle
public class Vehicle { public static void checkDrive() { System.out.println("checking Drive in the vehicle"); } public void pressHorn() { System.out.println("pressing horn in the vehicle"); } }
Truck
extends Vehicle
class and overrides instance method pressHorn
and static method checkDrive
. The Truck
class implementation is shown below.
Truck Class
public class Truck extends Vehicle { public static void checkDrive() { System.out.println("checking Drive in the Truck"); } public void pressHorn() { System.out.println("pressing horn in the Truck"); } public static void main(String[] args) { Vehicle vehicle = new Vehicle(); Truck truck = new Truck(); vehicle.checkDrive(); vehicle.pressHorn(); truck.checkDrive(); truck.pressHorn(); } }
The command below executes the above code snippet:
Run Command
javac Truck.java java Truck
The output of the executed command is shown below.
2.4.6 Java Abstract Class
An abstract class is used to hide the implementation and functionality from the user. The methods of an Abstract class can be abstract and non-abstract. An abstract class cannot be instantiated. The example below shows the implementation of Abstract class Person
.
Abstract Class
public abstract class Person { private String name; private String id; private int age; public Person(String name, String id, int age) { this.name = name; this.id = id; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public String getId() { return id; } public void setAge( int age) { this.age = age; } public void setName(String name) { this.name = name; } public void setId( String id) { this.id = id; } }
A subclass can be extended from the abstract class and you can implement abstract methods. An example below shows how Abstract Person
class can be extended by the Employee
Class.
DepartmentEmployee Class
public class DepartmentEmployee extends Person { public DepartmentEmployee(String name, String id, int age) { super(name,id,age); } public static void main(String[] args) { Person employee = new DepartmentEmployee("John Ray", "Dallas, TX", 43); System.out.println("Employee "+employee.getName()+" age " +employee.getAge()); }
The command below executes the above code snippet:
Run Command
javac DepartmentEmployee.java java DepartmentEmployee
The output of the executed command is shown below.
2.4.7 Polymorphism
In Java, a subclass can have their own behaviors. The example below shows the Parent class Shape
which is abstract and has abstract methods such as print
and getArea
.
Shape Class
public abstract class Shape { private int x; private int y; public Shape(int x, int y) { this.x = x; this.y = y; } public void moveTo(int x, int ny) { this.x = x; this.y = y; } abstract void print(); abstract void getArea(); }
Polygon
class extends Shape
class. The Polygon
class has print
and getArea
methods implemented. The code sample for Polygon
class is shown below.
Polygon Class
public class Polygon extends Shape { public Polygon(int x, int y) { super(x,y); } public void print() { System.out.println("Printing a polygon"); } public void getArea() { System.out.println("Polygon area"); } }
Triangle
class extends Shape
class. The Triangle
class has print
and getArea
methods implemented. The code sample for Triangle
class is shown below.
Triangle Class
public class Triangle extends Shape { public Triangle(int x, int y) { super(x,y); } public void print() { System.out.println("Printing a Triangle"); } public void getArea() { System.out.println("Triangle area"); } }
Polymorphism example is shown below. Polygon
and Triangle
objects are instantiated. print
and getArea
methods of the Shape
objects are invoked and the appropriate methods of Polygon
and Triangle
are executed.
Polymorphism Example
public class PolymorphismExample { public static void main(String[] args) { Shape polygon = new Polygon(3,4); Shape triangle = new Triangle(5,6); polygon.print(); triangle.print(); polygon.getArea(); triangle.getArea(); } }
The command below executes the above code snippet:
Run Command
javac PolymorphismExample.java java PolymorphismExample
The output of the executed command is shown below.
2.4.8 Java Nested Classes
Nested class is part of a Java class as a member. The nested class can be declared at private, public, protected or package levels. A sample class is provided below how a Shape
nested class is defined within a NestedClass
.
Nested Class
public class NestedClass { public String identifier = "23423"; class Shape { public String name; void setName(String name) { this.name = name; } } public static void main(String... args) { NestedClass nested = new NestedClass(); NestedClass.Shape shape = nested.new Shape(); shape.setName("Triangle"); System.out.println(shape.name); } }
The command below executes the above code snippet:
Run Command
javac NestedClass.java java NestedClass
The output of the executed command is shown below.
2.4.9 Java Inner Classes
Inner classes are defined within a java class. The example below shows DoubleCollection
class. DoubleCollectionIterator
interface is a subclassed from java.util.Iterator<Double>
. DoubleIterator
is an inner class which implements DoubleCollectionIterator
. Print
method of DoubleCollection
iterates through the DoubleIterator
for printing the double values from the collection.
Inner Class
public class DoubleCollection { private final static int SIZE = 25; private double[] arrayOfDoubles = new double[SIZE]; public DoubleCollection() { for (int i = 0; i < SIZE; i++) { arrayOfDoubles[i] = i; } } public void print() { DoubleCollectionIterator doubleCollIterator = this.new DoubleIterator(); System.out.println("Iterating through the collection"); while (doubleCollIterator.hasNext()) { System.out.print(doubleCollIterator.next() + " "); } System.out.println(); } interface DoubleCollectionIterator extends java.util.Iterator { } private class DoubleIterator implements DoubleCollectionIterator { private int nextInd = 0; public boolean hasNext() { return (nextInd <= SIZE - 1); } public Double next() { Double doubleValue = Double.valueOf(arrayOfDoubles[nextInd]); nextInd += 1; return doubleValue; } } public static void main(String s[]) { DoubleCollection collection = new DoubleCollection(); collection.print(); } }
The command below executes the above code snippet:
Run Command
javac DoubleCollection.java java DoubleCollection
The output of the executed command is shown below.
2.4.10 Java Local Classes
A local class can be defined within a static method of a java class. The example below shows the implementation of a Local Class. BlockLocalClass
has a static method validateSocialSecurityNumber
which has a local class SocialSecurityNumber
. Two social security numbers are validated with a regular expression. The rule for the regular expression checks for numerical digits. The length of a social security number is 8.
Local Class
public class BlockLocalClass { static String socSecValExp = "[^0-9]"; public static void validateSocialSecurityNumber( String socSec1, String socSec2) { int length = 8; class SocialSecurityNumber { String formattedSocSecNumber = null; SocialSecurityNumber(String socSecNumber){ String currNum = socSecNumber.replaceAll( socSecValExp, ""); if (socSecNumber.length() == length) formattedSocSecNumber = currNum; else formattedSocSecNumber = null; } public String getSocSecNumber() { return formattedSocSecNumber; } } SocialSecurityNumber num1 = new SocialSecurityNumber(socSec1); SocialSecurityNumber num2 = new SocialSecurityNumber(socSec2); if (num1.getSocSecNumber() == null) System.out.println("This Social Security number is invalid"); else System.out.println("This Social Security number" + num1.getSocSecNumber()); if (num2.getSocSecNumber() == null) System.out.println("This Social Security number is invalid"); else System.out.println("This Social Security number" + num2.getSocSecNumber()); } public static void main(String... args) { validateSocialSecurityNumber("23456789", "567890124"); } }
The command below executes the above code snippet:
Run Command
javac BlockLocalClass.java java BlockLocalClass
The output of the executed command is shown below.
2.4.11 Java Anonymous Classes
Anonymous Classes in java can be defined in an expression. The example below shows the implementation of an Anonymous Class. Anonymous Class has an interface Product
and a public method getProductOfTwoNumbers
. Inside the method, ProductApp
class implements the Product interface. The Product
interface has two methods printProduct
and getProduct
. ProductBase2
is created within a new expression.
Anonymous Class
public class AnonymousClass { interface Product { public void printProduct(int num1, int num2); public int getProduct(int num1, int num2); } public void getProductOfTwoNumbers() { class ProductApp implements Product { public void printProduct(int num1,int num2) { int product = getProduct(num1,num2); System.out.println("The product of two numbers " + num1 + ","+ num2+" is "+product); } public int getProduct(int num1, int num2) { int product = num1 * num2; return product; } } Product productBase10 = new ProductApp(); Product productBase2 = new Product() { public void printProduct(int num1,int num2) { int product = getProduct(num1,num2); System.out.println("The product of the numbers " + num1 + ","+ num2+" is "+product); } public int getProduct(int num1, int num2) { int product = num1 * num2; int prodBase2 = Integer.parseInt(Integer.toBinaryString(product)); return prodBase2; } }; productBase10.printProduct(7,5); productBase2.printProduct(4,10); } public static void main(String... args) { AnonymousClass anon = new AnonymousClass(); anon.getProductOfTwoNumbers(); } }
The command below executes the above code snippet:
Run Command
javac AnonymousClass.java java AnonymousClass
The output of the executed command is shown below.
2.4.12 Java Lambda Expressions
A java lambda expression has a list of parameters. These parameters are comma separated and enclosed by parentheses. The arrow token starts from the return value to the lambda expression. The example below shows the implementation of FloatOperations
Class. FloatMath
is an interface with Operation
method. FloatMath
sum and product operations are defined below as lambda expressions.
Lambda Expressions
public class FloatOperations { interface FloatMath { float operation(float a, float b); } public float executeFloatOp(float a, float b, FloatMath fm) { return fm.operation(a, b); } public static void main(String... args) { FloatOperations floatOps = new FloatOperations(); FloatMath sumOp = (a, b) -> a + b; FloatMath productOp = (a, b) -> a * b; System.out.println("23 + 25 = " + floatOps.executeFloatOp(23, 25, sumOp)); System.out.println("12 * 9 = " + floatOps.executeFloatOp(12, 9, productOp)); } }
The command below executes the above code snippet:
Run Command
javac FloatOperations.java java FloatOperations
The output of the executed command is shown below.
2.4.13 Java Enum Types
Java Enum type is defined a set of constants. Enum variable can be one of the defined values. An enum can have a constructor, properties and methods. The example below shows a Java Enum type with a default constructor. Direction
is the enum type. It has direction values. DirectionEnum
class has showDirections method which checks the direction value and prints the direction message.
Enum Type
public class DirectionEnum { public enum Direction { NORTH, SOUTH, WEST,EAST, NORTHWEST,NORTHEAST,SOUTHWEST,SOUTHEAST } Direction direction; public DirectionEnum(Direction direction) { this.direction = direction; } public void showDirections() { switch (direction) { case NORTH: System.out.println("Head North"); break; case SOUTH: System.out.println("Head South"); break; case WEST: System.out.println("Head West"); break; case EAST: System.out.println("Head East"); break; case NORTHWEST: System.out.println("Head NorthWest"); break; case NORTHEAST: System.out.println("Head NorthEast"); break; case SOUTHWEST: System.out.println("Head SouthWest"); break; case SOUTHEAST: System.out.println("Head SouthEast"); break; default: System.out.println("Please check your direction"); break; } } public static void main(String[] args) { DirectionEnum dir1 = new DirectionEnum(Direction.NORTH); dir1.showDirections(); DirectionEnum dir2 = new DirectionEnum(Direction.SOUTHWEST); dir2.showDirections(); try { DirectionEnum dir3 = new DirectionEnum(Direction.valueOf("Current")); dir3.showDirections(); } catch(Exception exception) { System.out.println("Please check your direction"); } } }
The command below executes the above code snippet:
Run Command
javac DirectionEnum.java java DirectionEnum
The output of the executed command is shown below.
2.4.14 Java Serialization
Java classes can be defined as serializable by implementing java.io.Serializable
interface. Serializable
is a java interface. This interface provides the capability for making a java class serializable. The example below shows the implementation of Product
class. The Product
class has SerialVersionUID
property defined. Serializer
class has methods to serialize and deserialize the java objects.
Serialization
import java.io.*; class Product implements java.io.Serializable { private static final long serialversionUID = 129348938L; public int id; public String name; public Product(int id, String name) { this.id = id; this.name = name; } } class Serializer { public void serialize(Object object, String fileName) { try { FileOutputStream fileOutput = new FileOutputStream(fileName); ObjectOutputStream output = new ObjectOutputStream(fileOutput); output.writeObject(object); output.close(); fileOutput.close(); System.out.println("The Product Object is serialized to a file"); } catch(Exception exception) { System.out.println("Exception has happened"); } } public void deSerialize(String fileName) { try { FileInputStream fileInput = new FileInputStream(fileName); ObjectInputStream input = new ObjectInputStream(fileInput); Product product = (Product) input.readObject(); input.close(); fileInput.close(); System.out.println("The Product Object is deserialized from a file"); System.out.println("id = " + product.id); System.out.println("name = " + product.name); } catch(Exception exception) { System.out.println("Exception has happened"); } } public static void main(String[] args) { Product product = new Product(14, "Truck"); String fileName = "output.ser"; Serializer serializer = new Serializer(); serializer.serialize(product,fileName); serializer.deSerialize(fileName) ; } }
The command below executes the above code snippet:
Run Command
javac Serializer.java java Serializer
The output of the executed command is shown below.
2.4.15 Java Application – Classes and Objects
Chaturanga is an indian version of chess. Chaturanga has two colors and eight pieces for each color. The example below shows the implementation of Chaturanga Piece
class.
Piece
public class Piece { private int position; private int color; private String currPosition; public final static int WHITE = 1; public final static int BLACK = 2; public final static int RATHA = 1; public final static int ASHVA = 2; public final static int GAJA = 3; public final static int MANTRI = 4; public final static int RAJA = 5; public final static int GAJA2 = 6; public final static int ASHVA2 = 7; public final static int RATHA2 = 8; public Piece(int position, int color) { this.position = position; this.color = color; } public int getPosition() { return position; } public int getColor() { return color; } public String getCurrPosition() { return currPosition; } public void setColor(int color) { this.color = color; } public void setPosition(int position) { this.position = position; } public void setCurrPosition(String currPosition) { this.currPosition = currPosition; } }
Chaturanga Board is a 8×8 grid. One side has white colored pieces and the other side has black colored pieces. The implementation of the ChaturangaBoard
is shown below:
Chaturanga Board
import java.util.*; public class ChaturangaBoard { public static int numColors = 2; public static int numPositions = 8; private Piece[][] pieces; public ChaturangaBoard() { pieces = new Piece[numColors][numPositions]; for (int color = Piece.WHITE; color <= Piece.BLACK; color++) { for (int position = Piece.RATHA; position <= Piece.RATHA2; position++) { pieces[color-1][position-1] = new Piece(position, color); } } } public Piece getPiece(int position, int color) { return pieces[color-1][position-1]; } }
DisplayChaturangaBoard
is a class which displays the pieces in a ChaturangaBoard
. The implementation of the class is shown below.
DisplayChaturangaBoard
import java.util.*; public class DisplayChaturangaBoard { public static void main(String[] args) { ChaturangaBoard board = new ChaturangaBoard(); for (int color = Piece.WHITE; color <= Piece.BLACK; color++) { for (int position = Piece.RATHA; position <= Piece.RATHA2; position++) { Piece piece = board.getPiece(position, color); System.out.println("Chaturanga "+color+" piece at "+ position); } } } }
The command below executes the above code snippet:
Run Command
javac DisplayChaturangaBoard.java java DisplayChaturangaBoard
The output of the executed command is shown below.
2.5 Best Practices
A Java class must have an identity. The behavior of the class is represented by methods. The state of the object is captured in the properties of the class. A class needs to have at least a default constructor. Objects are created by using new keyword, Class.forName(String className).newInstance()
and clone
method on the Object class. Objects are used to pass and return a single unit of information. The equalTo
method needs to be implemented to check for equality. Clone
method helps in creating a copy of the object. toString
method implementation has the string version of the object.
2.6 Error Handling
If private properties of a class are accessed, compiler throws an error. The setters and getters are used to access the private properties of a class. Private methods cannot be accessed from outside the class. The compiler shows the error. Class needs to have public methods which will, in turn, invoke the private methods. Garbage collector releases the memory of the objects which are no longer used. gc
method on the Runtime runs the garbage collector. Finalize
method is overridden in a class to release the system resources. This method performs a clean up of the resources which are not released.
2.7 Code Conventions
The Java code conventions for classes and objects can be found at the oracle site.
3. Download the Source Code
You can download the full source code of this example here: Java Classes and Objects Tutorial
Last updated on Oct. 09, 2019