O'Reilly logo

Java 7 Pocket Guide, 2nd Edition by Patricia Liguori, Robert Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

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

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.

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 a Class (Creating ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required