Classes and Objects in Java

Video Tutorial
FREE
Classes & Objects I thumbnail
This video belongs to
Java Course - Mastering the Fundamentals
12 modules
Certificate
Topics Covered

Java is a class-mandatory programming language that imposes an object model on the developer. Classes serve as a prototype for representing objects that group pieces of data and methods. An Object is an entity that has a state and behaviour. As a result, we think of a problem in the world in terms of objects and perform actions by calling their associated set of methods.

The concept of class and object in Java is quite useful in development as well as solving sophisticated problems.

Java Classes

In Java, a class serves as a blueprint for creating objects with similar characteristics and behaviours. It encapsulates properties and meaning within a specific context, like a Car class representing individual cars. Classes maintain common attributes and behaviours, facilitating efficient object creation and management in programming.

Properties of Java Classes

  • A Java class serves as a blueprint for creating objects and doesn't take up memory.
  • It comprises variables of various types and methods. You can include data members, methods, constructors, nested classes, and interfaces within a class.
  • It acts as a template for organizing and defining the behaviour of objects in your program.

Syntax of Java Classes

One can declare a public, private, or default class as:

Example of Java Class

Let's see an example for syntax of class and object in Java:

The code above shows a template for how class and object in Java are implemented. The Car class contains private attributes hidden from the outside world. That means calling out the modelName attribute outside the scope of the Car class will raise a compiler error.

Components of Java Class

Class Name

The class name pertains to a namespace in which we can associate coherent methods and data. In our code example, both ClassA and ClassC pertain to a class's namespace. Java uses a PascalCase naming convention for classes.

Class keyword

The class keyword signifies that we intend to begin creating a prototype of an object.

Constructors

Java constructors initialize an instantiated object based on preconditions set by the caller. Constructors can be parameterized or specified without parameters.

A class may contain multiple constructors that configure an instantiated object accordingly. A constructor is a specialized method that must be defined with:

  1. The same name as the class.
  2. Does not return an explicit type.
  3. Cannot be synchonized, abstract, static, and final.

We say a constructor is defined in default when it contains no parameters. Default constructors are intended to initialize an object when no arguments are passed into it. A constructor is overloaded whenever we specify parameters.

Modifiers

Java supports access modifiers to provide different restriction levels in different program parts. In other words, access modifiers control which code sections can invoke the name of a class, method, or attribute. There are two contexts in which an access modifier may be defined: memberwise access and class-level access.

Suppose that we subclass Sphere from PackageTwo in AbstractShape from PackageOne as follows:

modifiers in java

Suppose further that in each class, an entity exists with different modes of access.

Summary of the visible entities relative to ClassA:

ModifierSphereAbstractShapeCube
publicvisiblevisiblevisible
protectedvisiblevisiblenot visible
[default]visiblevisiblenot visible
privatevisiblenot visiblenot visible

In general, the table translates to:

Access ModifierWithin ClassWithin SubclassWithin packageOutside Package
PrivateVisibleNot VisibleNot VisibleNot Visible
[Default]VisibleNot VisibleVisibleNot Visible
ProtectedVisibleVisibleVisibleNot Visible
PublicVisibleVisibleVisibleVisible

Body

The body of the class contains the implementation of associated methods and attributes within that class. A body may contain the following:

  • Methods contain the set of actions in the object definition,
  • Constructor, which is a unique method that initializes the state of an object upon its creation,
  • Attributes that define the internal states of the class, and
  • Variables that contain the values of an attribute within the class In addition, methods and attributes may be specified with modifiers that regulate their accessibility.

Superclass (or Supertypes)

superclass

Superclass may be implemented as abstract class or base class types because they contain a group of standard features that are extended in a subclass. Because subclass extends the contents of a superclass, Java uses the keyword class [classname] extends [superclass].

Superclass contains the following features that extend your Object-Oriented Design:

  1. A superclass represents a set of common properties inherited by its subclass. A subclass may modify methods that maintain the structure of an interface with altered behaviour.
  2. Supertypes may implicitly cast a type into its subtype when the situation calls for it.

Suppose we intend to pass an argument in a function. Since Java expects type information before the name of an argument, we need to include it. Without supertypes, we would have to overload multiple functions to account for executing the same method in different types.

To get rid of code redundancy, supertypes are a great way for the compiler to deduce the type information based on the argument passed into the function.

Now, displayInformation() can accept any subtypes that extend from AbstractShape, such as the class Cube.

Interface

Because Java does not support multiple inheritance, subclasses can only extend one superclass. This limitation is addressed by a Java construct known as Interfaces.

An interface is a set of declarations that form a contract between an object and the outside world. If the class intends to use the interface, all its methods must appear in the source code; otherwise, the program will not compile. All methods defined in an interface default to public final static.

Note that since Java 8, an interface can define a default method with the default keyword.

Java Objects

Objects model an entity in the real world. Modeling entities require you to identify the state and set of actions that can be performed in that object. This way of thinking is key to object-oriented programming.

  • An Object is the root class of all instantiated objects in Java.
  • Instantiated objects are names that refer to an instance of the class.

Declaring Objects in Java

The first two tokens in the code snippet above declare an object in Java. When we read into the code, it means creating a new instance of Sphere and initializing its radius to 10.

Initializing a Java object

As mentioned, a constructor initializes an object in Java. Multiple class constructors mean that instantiating an object can have different signatures. We use the new NameOfClass([arguments_values])) to initialise a new object. There are mainly three ways to initialize an object in Java:

By Reference Variable

A constructor may accept reference type parameters.

Recall: All object types in Java are passed by reference.

Example: Initialization through reference

The above code effectively copies the content of arguments passed in the constructor of type Cube.

By method

An object may be initialized with a setter function that alters the class's internal state and may be accessed with a getter function. This initialization allows only one instance of the class to be modified dynamically: one can alter that of the object at runtime.

Example: Initialization through a method

By constructor

Finally, an object may be initialized by specifying arguments passed in a constructor. A constructor is a unique method that initializes the state of class instance.

Different Ways to Create Objects in Java

There are different ways to instantiate an object in Java; this section aims to discuss and implement each style.

Using new Keyword

This is the most direct form of object creation in Java. This style tells Java to initialize a class instance and assign a reference to it in a named object, in this case, cube.

Using Class.forName(String className) Method

This style can be attained if the class has a public constructor. The Class.forName() method does not yet instantiate an object; to do so, the newInstance() has to be typecast in the given class.

Using clone() Method

It requires the object to implement a Cloneable interface. Since objects are passed by reference in Java, changes that happen somewhere in the program affect the internal state of that object. In cases where we do not want unintended side effects to happen, we can copy the entire contents of an object and treat it independently.

Deserialization

It converts a stream of bytes into an object. We must implement the Serializeable interface in the class to implement this style.

Anonymous Objects in Java

Anonymous objects are nameless entities that may be used for calling a specific method defined in a class without needing the entire class – nameless objects mean the class instance does not have a reference.

Creating Multiple Objects by One Type

One can create multiple objects within a container type in Java, such as List, Array, ArrayList, Queue, and Stack.

Real World Example: Account

Difference between Classes and Objects in Java

ClassObject
A class is a blueprint for declaring and creating objects.An object is a class instance that allows programmers to use variables and methods from inside the class.
Memory is not allocated to classes. Classes have no physical existence.When objects are created, they are allocated to the heap memory.
You can declare a class only once.A class can be used to create many objects.
Class is a logical entity.An object is a physical entity.
We cannot manipulate class as it is not available in memory.Objects can be manipulated.
Class is created using the class keyword like class Dog{}Objects are created through new keyword like Dog d = new Dog();. We can also create an object using the newInstance() method, clone() method, factory method, and deserialization.
Example: Mobile is a class.If Mobile is the class, then iphone, redmi, blackberry, and samsung are its objects with different properties and behaviours.
Classes can have attributes and methods defined.Objects can have specific values assigned to their attributes.
Classes serve as blueprints for creating objects.Objects represent specific instances created from a class.

To learn about differences between class and object in Java depth, visit Class Vs. Object: What are the Differences?

Conclusion

  • Objects are models of an entity that exist in the real world. Object-oriented thinking refers to everything as objects that contain a set of states and behaviour.
  • Class provides a prototype for describing the content of an instantiated object.
  • The most straightforward declaration of a class contains a class name and a class body, which may contain constructors, methods, and attributes.
  • A class may extend features from another class, which preserves the interface of standard features and allows a subclass to specialize methods accordingly.
  • Classes may take in three forms: Abstract, Base, and Concrete class.
  • Java does not support multiple inheritance; Interfaces substitute multiple inheritance by defining a contract between classes.