Classes and Objects in Java
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 behavior. 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.
What is a Class in Java?
A class in Java represents a concept that maintains a set of properties that encapsulate the meaning-making within that context. For instance, one might represent a Car with its components and associated actions in a class. Our model of a car contains modelName, regNumber, and owner as attributes and startEngine(), accelerate(), and stop() as methods.
The code above shows a template for how classes are implemented in Java. 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.
Note that we cannot interact directly with a class. It has to be instantiated, which makes the class a model of an object. To instantiate a class, we call its constructor as follows:
In terms of design, there are three types of classes in Java:
- Concrete class - represents a concrete form of an object that may or may not be extended. Like a base class, one can extend a concrete class. But once specified as final a concrete class can no longer be extended.
- Abstract class - represents a set of rules that a concrete class must satisfy. An abstract class may contain default implementation and abstract methods, which we will discuss in this section (Superclass or Supertypes). Additionally, one cannot create an instance of an abstract class because it is meant to create a prototype of a class – not an object instance.
- Base class - represents a parent class that other classes may extend. Unlike an abstract class, base classes cannot contain abstract methods, so extending base classes will inherit the properties associated with the base class. Furthermore, one can instantiate an object of a base class.
Syntax of Java Class
This section contains the template for writing valid expressions inside a class in Java.
The bracketed symbols pertain to variables that can be substituted to any one of the defined set of keywords separated by |. One can declare a public, private, or default class as:
Symbols preceded with -- denote an optional variable that may or may not be substituted with a keyword. That means it is equally valid to have written public final class ClassName as public class ClassName, and as class ClassName. Adding qualifiers and modifiers will affect the meaning of our program, which will be discussed later in this section (Components of a class).
In relation to the previous section, the following types of classes are declared as follows:
Note that the extends clause and the final modifier are optional as denoted by the –- [type] -- expression in the description of the syntax. Concrete examples are provided in the later in this section (Components of a class).
Components of a Class
This section discusses the meaning of keywords appended to the class declaration and the components that can be defined inside a class in Java. Let us see examples of how we might represent shapes as classes. We begin by representing all shapes by declaring the set of common properties expected from every shape as follows:
The process of grouping together common features is known as abstraction, in the code shown above, we defined a set of properties that has to be implemented in our subclass.
The class name pertains to a namespace in which we can associate a coherent set of 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.
The class keyword signifies that we intend to begin creating a prototype of an object.
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:
- The same name as the class.
- Does not return an explicit type.
- Cannot be synchonized,abstract,static, and final.
We say that a constructor is defined in default when it contains no parameters. Default constructors are intended to initialize an object when there are no arguments passed into it. A constructor is overloaded whenever we specify parameters.
Java supports access modifiers for providing different restriction levels in different parts of the program. In other words, access modifiers control which code sections can invoke the name of a class, method, or attribute. There are two contexts in that an access modifier may be defined: memberwise access and class-level access.
A memberwise access pertains to modes of access that are regulated on entities that belong to a class, i.e., attributes and methods, while class-level access regulates accessing the class itself.
Suppose that we subclass Sphere from PackageTwo in AbstractShape from PackageOne as follows:
Suppose further that in each class, there exists an entity with different modes of access.
Summary of the visible entities relative to ClassA:
|private||visible||not visible||not visible|
In general, the table translates to:
|Access Modifier||Within Class||Within Subclass||Within package||Outside Package|
|Private||Visible||Not Visible||Not Visible||Not Visible|
|[Default]||Visible||Not Visible||Visible||Not Visible|
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 special 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 may be implemented as abstract class or base class types because they contain a group of common features that are extended in a subclass. Because subclass extend the contents of a superclass, Java uses the keyword class [classname] extends [superclass].
Superclass contains the following features that extend your Object-Oriented Design:
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 behavior. In other words, a subclass can define the specific meaning of operations for its context i.e. the surfaceArea() of a sphere is defined as while the surfaceArea() of a cube is defined as .
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.
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 serves as a set of declarations that forms a contract between an object and the outside world. That is, 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.
The interface contains a set of abstract methods that are expected to be defined in a class that implements the interface. Like an abstract class, interfaces cannot be instantiated. In addition, a class may implement multiple interfaces while extending from a supertype simultaneously.
Note that since Java 8, an interface can define a default method with the default keyword.
What is an Object in Java?
Objects model an entity that exists 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.
It is important to disambiguate an Object with an instantiated object in Java.
- 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 to create a new instance of Sphere and initialize its radius to 10.
Initializing an Object in Java
As mentioned, a constructor initializes an object in Java. Multiple class constructors mean that instantiating an object can have different signatures. To initialize a new object, we use the new NameOfClass([arguments_values]).
Characteristics of Java Object
An object in Java contains:
- State - internal representation of the state of an object
- Behavior - methods or actions associated with an object
- Identity - name that is implemented with a unique ID
Ways to Create an Object in Java
There are different ways to instantiate an object in Java; this section is aimed at discussing and implementing each style.
Using the new Keyword - 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. Class.forName() method does not yet instantiate an object, to do so, the newInstance() has to be type cast in the given class.
Using clone() method - requires the object to implement 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 - converts a stream of bytes into an object. To implement this style, we must implement the Serializeable interface in the class.
By Factory Method - is a method defined in a Factory Design Pattern that provides an interface for creating new objects. This is considered flexible as instantiating multiple subclasses from a superclass can be called directly from the FactoryClass. To implement this style, we need to make substitute a class that constructs the makeShape() of the object to be instantiated.
What are Anonymous Objects?
Anonymous objects are nameless entities that may be used for calling a specific method defined in a class without ever needing the entire class – nameless objects mean the class instance does not have a reference.
How to create multiple objects by one type only
One can create multiple objects within a container type in Java, such as List, Array, ArrayList, Queue, and Stack.
Real World Example: Account
The main method signifies the entry point of execution in the Java program.
Example 1: main within the class
Example 2: main outside the class
3 Ways to initialize an object
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 that is of type Cube.
An object may be initialized with a setter function which alter the internal state of the class and may be accessed with a getter function. This way of 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
Finally, an object may be initialized by specifying arguments passed in a constructor. A constructor is a special method that initializes the state of class instance.
Example: Initialization through a constructor
We have seen this style before:
Benefits of Classes and Objects in Java
In Java classes an, objects have three main benefits:
- Modularity. Objects may be broken down and composed with one another, that is a mental model of an object may be modularized into different parts that can work with each other.
- Abstraction. In object-oriented programming, we think of a model-driven approach to solve the problem, which results to an abstract representation of the world where we can conveniently describe our solution.
- Reusability. Classes provide a prototype for the instantiated object, this prototype remains consistent with all instances of the class, so we do not have to reimplement methods as they are defined in an object. In addition, subclassing extends the code of a superclass to suit another object.
Objects are models of an entity that exist in the real world. Object-Oriented thinking comes from regarding everything as Objects which contains a set of states and behavior.
Class provide a prototype for describing the content of an instantiated object.
The simplest declaration of a class contains a class name and a class body which may contain constructors, methods, and attributes. But a class can be declared with superclass and interfaces, which extend the definition of a class.
A class may extend features from another class which preserves the interface of common features and allows a subclass to specialize methods accordingly.
Classes may take in three forms: Abstract, Base, and Concrete class.
Since Java does not support multiple inheritance, Interfaces substitute multiple inheritance by defining a contract between classes. An interface cannot be instantiated.