Java Classes and Objects. Abstract Classes and Interfaces. Constructors, Getters and Setters

Java Objects and Classes

Classes and objects are foundation stones of Java programming language. Java classes and objects are building blocks of Java programs. Java is a pure object oriented programming language therefore every problem is implemented with help of classes and objects. A Java class is a type definition or a blueprint or a structure for objects that are created from the defined class. In more general way a Java class defines how an object is implemented in during Java program. Java being a pure object oriented programming language makes classes a mandatory programming construct for solving problems. A Java class may contain one or more classes within itself. These internal classes are called Java’s nested classes. Studying classes and objects in Java is a large topic and cannot be covered under one article. This tutorial explains Java class definition and its most common parts.

In the simplest way, a Java class definition consists of the keyword class followed by the name of the class then the body enclosed in braces. The body of a Java class contains data members (also called fields), member methods (or methods), constructors, instance and static initializer blocks, nested classes, and interfaces.

Members (data members, methods, member classes, member interfaces) of a Java class are accessible to entire body of the class which they belong to. Members of a Java class and its constructors include the access modifiers public, protected, or private. If no access modifier is mentioned then the member has default access. A class member having default access can be accessed within same class and package but not within from subclass and other packages.

Java Class Declaration

A Java class is declared using the class keyword and defines a new data or reference type. Ideally, a class declaration statement starts with optional class modifiers and then followed by keyword class, then class name, then optional type parameters (if it is a generic class), then optional extends to inherit a super-class, and then any number of interfaces which a class needs to implement. Following is the syntax of a normal Java class declaration:

ClassModifiersopt class Identifier TypeParametersopt Superopt
Interfacesopt ClassBody

In above Java class declaration syntax ClassModifiers can include Annotations and public, protected, private, abstract, static, final, strictfp keywords. The Identifier in a Java class declaration specifies the name of the class. The ClassBody is enclosed in opening '{' and closing '}' braces. Note that, more than one ClassModifiers can be specified for a class, but not all ClassModifiers are applicable to all kinds of class declarations. The modifiers that can be attached to a Java class declaration are described as follows:

  • annotations - Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
  • public - The access modifier public pertains only to top level classes and to member classes not to local classes or anonymous classes.
  • protected and private - The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration or enum declaration.
  • static - The access modifier static pertains only to member classes not to top level or local or anonymous classes.
  • abstract - makes a class abstract that cannot be instantiated, but can be subclassed. An abstract class may or may not include abstract methods, means if a class has an abstract method it must be declared abstract, but on the contrary if a class is declared abstract then it is not necessary for the class to include an abstract method. An enum type must not be declared abstract, or a compile-time error occurs. I will cover enums in a separate article. You are only allowed to declare a method abstract in enum body, if the enum has one or more enum constants with class bodies that provide concrete implementation of the abstract method.
  • final - class cannot be inherited further. If a class restricts itself from being inherited then it can be defined final. A final class must not be inherited. A class cannot be declared both abstract and final. Try doing that and you will get a compile time error. You may have guessed why is it? For a final class never has any subclasses, the methods of a final class cannot be overridden.
  • strictfp - makes all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict.
    strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability. It was introduced into Java with the Java virtual machine (JVM) version 1.2.

A compile-time error occurs if the same modifier appears more than once in a class declaration.

Java Abstract Class

An abstract class in Java can never be instantiated; its only purpose is for other Java classes to extend. The main purpose of Java's abstract class is to contain common code used in sub classes but the abstract class should not have instances of its own. A Java abstract class is considered to be incomplete because it may have one or more abstract methods those are yet to be defined.

A class is said to have abstract method, if any of the following is true:

  • If a class explicitly declares a method with abstract modifier
  • If a superclass has an abstract method that is not further implemented by the subclass then the subclass is said to have abstract method, or the subclass does not inherit a method which implements it.
  • If a class implements an interface that necessarily has one or more abstract method(s) and if the class neither declares nor inherits a method that implements those methods. Then the class is said to have abstract method.

An attempt to create an instance of an abstract class using a class instance creation expression will result into compile time error.

It would again be a compile time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods.

Note that an abstract Java class is a class that is declared with abstract modifier. An abstract Java class may or may not have abstract methods. We cannot create an instance of Java abstract class but we can inherit subclasses from it.

Java Class: A Working Example

A Java class defines a new data type, therefore a Java class is a template for a Java object, and an object is an instance of a class. A Java class is the smallest unit of Java code that can be compiled alone, however an interface is quite similar to a class. Here is a class Book to demonstrate the declaration and its functioning in a program. We will go through the internal parts of class Book one by one as they appear in the class.

/* */
public class Book
    private String bookTitle;
    private String bookAuthor;
    private int numOfPages;
    /* zero argument constructor */
    public Book ()
        bookTitle = null;
        bookAuthor = null;
        numOfPages = 0;  
    /* constructor with parameters */
    public Book (String bookTitle, String bookAuthor, 
                 int numOfPages)
        this.bookTitle = bookTitle;
        this.bookAuthor = bookAuthor;
        this.numOfPages = numOfPages;  
    public String getBookTitle()
        return bookTitle;
    public void setBookTitle(String bookTitle)
        this.bookTitle = bookTitle;
    public String getBookAuthor()
        return bookAuthor;
    public void setBookAuthor(String bookAuthor)
        this.bookAuthor = bookAuthor;
    public int getNumOfPages()
        return numOfPages;
    public void setNumOfPages(int numOfPages)
        this.numOfPages = numOfPages;

Above piece of code begins with comments. Now come to class declaration, the line public class Book declares a class Book of public access. Keyword public makes this class accessible from anywhere inside or outside the package. If the access modifier is omitted then a class by default remains accessible within the package in which the class has been defined.

Usually, Java classes are defined in separate files where one file contains one class and the file name is identical to the class name having .java extension. But more than one class can also be written in a file; and in that case, only one class can be declared public and remaining will be of default access. File name will be in the name of public class if there is more than one class coded in one file.

Conclusively, the best practice is to keep all class or enum or interface definitions in separate files. It is assumed clean and unambiguous approach of code writing.

Entering into the body of the Java class Book we see three data members named as bookTitle, bookAuthor, and numOfPages, where none of them are declared static. So there are no class level members. All members declared inside class body will be object level members. They all declared private to the class and therefore cannot be accessed outside the class. Now come to constructors.

Java Class: Parameterized Constructor

In the body of Java class Book below the declaration of data members you see function-definition like structures with the same name as the class name. These are constructors. Constructors have same name as the class name. Here, for Book class two constructors have been defined - one without parameters (zero argument or with no argument), and second with parameters (parameterized constructor or constructor with parameters). If you define a parameterized constructor in a class then it is mandatory to define zero argument constructor in order to create an object with no argument in object creation expression (using new operator).

A constructor runs when an object of a Java class is created. A constructor can be seen as a method definition that has no return type, and that's name is identical to the class name. Java Language Specification gives the following syntax to define a constructor in a class:

ConstructorModifiersopt TypeParametersopt SimpleTypeName (FormalParameterListopt) Throwsopt 
   //Constructor Body
*SimpleTypeName is the name of the constructor and it 
is similar to the class name.
Constructor modifiers can be one of:
Annotation public protected private
If no access modifier is specified for the constructor of a normal 
class, the constructor has default access.

Java constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding. A Java constructor is invoked at following three occasions:

  • By class instance creation expressions (when object is created using new operator)
  • By the conversions and concatenations caused by the string concatenation operator (+).
  • And by explicit constructor invocations from other constructors.

Note that Java constructors are never invoked by method invocation expressions (object-name.constructor-name). Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized.

  • A Java constructor is not needed to declare final because it is not inherited.
  • An abstract Java constructor could never be implemented.
  • Making a Java constructor to be static makes no sense because a constructor is always invoked in respect to an object.
  • The throws clause for a constructor is identical in structure and behavior to the throws clause for a method.

In body of a Java constructor data members are initialized. The first statement of a Java constructor's body may be an explicit invocation of another Java constructor of the same class or of the direct superclass.

There will be a compile-time error for a Java constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.

If a Java constructor's body does not begin with an explicit constructor invocation and the constructor being declared is not part of the class Object, then the constructor body implicitly begins with a superclass constructor invocation super();, an invocation of the constructor of its direct superclass that takes no arguments.

A return statement with no return value may be used in the body of a constructor.

Java Class: Default Constructor

Sometimes, when you don't feel a need to initialize data members by particular values then you can skip writing constructors at all. In that case the Java compiler automatically creates a constructor with zero arguments that does nothing. This default constructor allocates memory and initializes instance variables by default values.

Here, it is important to know that once programmer defines one or more parameterized constructors then Java does not internally create default constructor. In that situation developers have to create a zero argument constructor at their own.

Java Class: Accessors and Mutators or Getters and Setters

While writing new Java classes we pay much attention to information hiding, where we ensure the data members should be declared private if programmers don't feel an explicit need to declare them public or default. As we know private members of a class cannot be accessed outside the class yet you can allow other classes to find out what their values are by providing public accessor methods. Class Book defines three accessors or getters for all three members as getBookTitle(), getBookAuthor(), getNumOfPages(), and three mutators or setters as setBookTitle(String bookTitle)(), setBookAuthor(String bookAuthor), and setNumOfPages(int numOfPages).

Not all fields need individual field accessors and mutators. It will depend on the business logic written in a class.

Now, let's quickly create a class BookDemo to demonstrate object creation and data member access.

/* */
class BookDemo 
  public static void main(String args[])
    Book b = new Book("James Gosling", "The Java Language Specification", 670);
    System.out.println("Book's Author: " + b.getBookAuthor());
    System.out.println("Book's Title: " + b.getBookTitle());
    System.out.println("Number of Pages: " + b.getNumOfPages());
Book's Author: The Java Language Specification
Book's Title: James Gosling
Number of Pages: 670

In class BookDemo when the statement Book b = new Book("James Gosling", "The Java Language Specification", 670); is executed it creates an object in memory by calling the parameterized constructor of class Book then newly created object is assigned to the reference b. Values of all data members are then printed on console by invoking accessors defined in Book.

Last Word

In this tutorial we talked of Java classes and objects. During Java classes we talked of Java class declaration, abstract Java classes, and abstract methods. We also discussed default constructor, parameterized constructor, and accessors (getter methods) and mutators (setter methods). Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!


Get Free Tutorials by Email

About the Author

is the main author for He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Facebook to exclude billions from European privacy lawsPosted on Thursday April 19, 2018

A total of 1.5 billion international Facebook users will not be protected under GDPR.

TalkTalk and Vodafone top complaints chart againPosted on Thursday April 19, 2018

TalkTalk, Vodafone and BT drew the most complaints for their services, the regulator says.

Ikea's TaskRabbit app back online after data breachPosted on Thursday April 19, 2018

The odd jobs marketplace has been investigating a "cyber-security incident".

Courtesy BBC News


Advertisements help running this site for free.

To view the content please disable AdBlocker and refresh the page.