Chapter 5. Object-Oriented Programming

Basic elements of object-oriented programming (OOP) in Java include classes, objects, and interfaces.

Classes and Objects

Classes define entities that usually represent something in the real world. They consist of a set of values that holds data and a set of methods that operates on the data.

Classes can inherit data members and methods from other classes. A class can directly inherit from only one class—the superclass. A class can have only one direct superclass. This is called inheritance.

An instance of a class is called an object, and it is allocated memory. There can be multiple instances of a class.

When implementing a class, the inner details of the class should be private and accessible only through public interfaces. This is called encapsulation. The JavaBean convention is to use accessor and mutator methods (e.g., getFirstName() and setFirstName("Leonardina")) to indirectly access the private members of a class and to ensure that another class cannot unexpectedly modify private members. Returning immutable values (i.e., strings, primitive values, and objects intentionally made immutable) is another way to protect the data members from being altered by other objects.

Class Syntax

A class has a class signature, optional constructors, data members, and methods:

[javaModifiers] class className
  [extends someSuperClass]
  [implements someInterfaces separated by commas] {
  // Data member(s)
  // Constructor(s)
  // Method(s)
}

Instantiating ...

Get Java Pocket Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.