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. Although not part of the Java language, the
convention is to use accessor methods (i.e., get( )
and
set( ))
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
] classclassName
[extendssomeSuperClass
] [implementssomeInterfaces separated by commas
] { // Data member(s) // Constructor(s) // Method(s) }
Instantiating a Class (Creating an ...
Get Java Pocket Guide 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.