Core Java
Objects and Classes
Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.

Copyright © Cay S. Horstmann 2016
Except where otherwise noted, this work is licensed under 
Understand the fundamental concepts of object-oriented programming
Why OOP?
- 1970s: “Structured” programming.
- Algorithms + Data Structures = Programs.
- Procedures operate on shared data.
- 1980s: Object-oriented programming.
- Each object has data and methods.
- Encapsulation: Only methods can access object data.

- Java is thoroughly object-oriented.
- Everything other than a primitive type value is an object.
Classes and Objects
- Class: “Cookie cutter” for objects.
- Describes object data and method behavior.
- Object = instance of class.
- Object has:
- OOP starts with identifying classes:
- Nouns are often classes:
Item
, Order
, and so on.
- Verbs are often methods:
add
an item to an order, ship
an order.
Work with predefined classes
Using Predefined Classes
Object Variables
Working with LocalDate
- A
Date
is a point in time, measured in UTC.
- A
LocalDate
is a date (day, month, year) in a particular location.
- Use factory methods to create instances:
LocalDate rightNow = LocalDate.now();
LocalDate newYearsEve = LocalDate.of(1999, 12, 31);
LocalDate
methods:
LocalDate aThousandDaysLater = newYearsEve.plusDays(1000);
year = aThousandDaysLater.getYear(); // 2002
month = aThousandDaysLater.getMonthValue(); // 09
day = aThousandDaysLater.getDayOfMonth(); // 26
- How is a
LocalDate
stored? How do these methods do their job? You don't know, and you don't care. That's encapsulation.
Accessor and Mutator Methods
- Accessor method doesn't modify object state.
- All
LocalDate
methods are accessors.
- Older version of calendar date class has mutator methods:
GregorianCalendar someDay = new GregorianCalendar(1999, 11, 31);
someDay.add(Calendar.DAY_OF_MONTH, 1000);
// someDay has been mutated
int year = someDay.get(Calendar.YEAR); // 2002
- Tip: Minimize mutator methods. They make it more difficult to share objects in concurrent programs.
CalendarTest
Define your own classes
Defining Your Own Classes
class Employee
{
// Fields
private String name;
private double salary;
private LocalDate hireDay;
// Constructors
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
hireDay = LocalDate.of(year, month, day);
}
// Methods
public String getName() { return name; }
. . .
}
Constructors
- In general, instance fields are private.
- Initialized in constructor:
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
hireDay = LocalDate.of(year, month, day);
}
- The call
new Employee("James Bond", 100000, 1950, 1, 1)
sets the fields as follows:
name = "James Bond";
salary = 100000;
hireDay = LocalDate.of(1950, 1, 1);
- Name of constructor = class name.
- Constructor only works with
new
.
Implicit and Explicit Parameters
- Methods access and modify fields:
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
- In the call
number007.raiseSalary(5)
, these steps occur:
double raise = number007.salary * 5 / 100;
number007.salary += raise;
- The call depends on two parameters:
byPercent
is an explicit parameter.
- The object on which the method is invoked is the implicit parameter.
- Can optionally use
this
to denote implicit parameter: public void raiseSalary(double byPercent)
{
double raise = this.salary * byPercent / 100;
this.salary += raise;
}
EmployeeTest
Benefits of Encapsulation
Understand advanced concepts of classes in Java
Final and Static Fields
- A
final
field cannot change:
private final String name;
- Caution: A
final
object can still be mutated:
private final StringBuilder evaluations;
public Employee() { evaluations = new StringBuilder(); . . . }
public void giveGoldStar() { evaluations.append("Gold star!\n"); }
- A
static
field exists once per class:
private static
int nextId; // one field per class
private int id; // one field per object
public void setId() { id = nextId; nextId++; }
- A
static final
field is a shared constant:
public class Math
{
public static final double PI = 3.14159265358979323846;
// Accessible anywhere as Math.PI
. . .
}
Static Methods
StaticTest
Understand parameter passing in Java
Call by Value

Call with Object References
Object References Are Passed by Value
- Some people say: “In Java, numbers are passed by value and objects are passed by reference.”
- That's nonsense. In Java, everything is passed by value.
- Object references are passed by value.
- If objects were passed by reference, you could swap them:

public static void swap(Employee x, Employee y) // doesn't work
{
Employee temp = x;
x = y;
y = temp;
}
But in the following call, a
and b
are not swapped:
Employee alice = new Employee("Alice", . . .);
Employee bob = new Employee("Bob", . . .);
swap(alice, bob);
ParamTest
Learn more about object construction
Overloading
- A class can have more than one constructor:
StringBuilder messages = new StringBuilder();
StringBuilder todoList = new StringBuilder("To do:\n");
- The constructor name is overloaded.
- Name + parameter types = Method signature.
- Overloading resolution: The compiler picks the appropriate version from the argument types.
- You can overload any method:
String.indexOf(int)
String.indexOf(int, int)
String.indexOf(String)
String.indexOf(String, int)
- The return type is not a part of the method signature.
Default Construction
Field Initialization
- You can override the 0/
false
/null
default for fields:
class Employee
{
private String name = "";
. . .
}
- The initialization value can be computed:
class Employee
{
private static int nextId;
private int id = assignId();
. . .
private static int assignId()
{
int r = nextId;
nextId++;
return r;
}
. . .
}
Construction Parameter Names
- Some programmers like single-letter parameter names:
public Employee(String n, double s)
{
name = n;
salary = s;
}
- For better documentation, can use
a
prefix:
public Employee(String aName, double aSalary)
{
name = aName;
salary = aSalary;
}
- Can use
this
to distinguish between parameters and fields:
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
Calling Another Constructor
Initialization Blocks
- Class declarations can contain arbitrary blocks of code.
- Executed whenever an object is constructed:
class Employee
{
private static int nextId;
private int id;
// object initialization block
{
id = nextId;
nextId++;
}
public Employee(. . .) { . . . } // constructor
. . .
}
- Static initialization block is executed when class is loaded:
static
{
Random generator = new Random();
nextId = generator.nextInt(10000);
}
ConstructorTest
Work with packages and imports
Packages
Imports
- Can access classes from any package with fully qualified name:
java.time.LocalDate today = java.time.LocalDate.now();
- Import statements remove the tedious repetition:
import java.time.*;
. . .
LocalDate today = LocalDate.now();
- Can import single class:
import java.time.LocalDate;
- Cannot have multiple wildcards (
import java.*.*
).
- If two packages import the same class, you still need fully qualified names:
import java.util.*;
import java.sql.*;
. . .
Date today; // Error--java.util.Date or java.sql.Date?
- Or add a disambiguating import to the wildcard imports:
import java.util.Date;
Static Imports
- Imports static fields and methods:
import static java.lang.System.*;
- Now you can refer to
System.out
and System.exit
without the class name:
out.println("Goodbye, World!"); // i.e., System.out
exit(0); // i.e., System.exit
- Can import a specific method or field:
import static java.lang.System.out;
- Can be handy for mathematical functions:
import static java.lang.Math.*;
. . .
r = sqrt(pow(x, 2) + pow(y, 2));
Adding a Class to a Package
PackageTest
Package Scope
The Class Path
Java 9 News Flash - Modules

- Modules are collections of packages.
- Implementation packages can be encapsulated.
- “Package private” features are not visible outside the module.
- An important feature for programming in the large.
- See Lesson 6 of Core Java 9 Advanced LiveLessons.
Use the javadoc
utility to produce class documentation
Documentation Comments
- Add comments delimited by
/** ... */
to source files.
javadoc
tool generates HTML documentation.
- Can document:
- Packages
- Public classes and interfaces
- Public and protected fields, constructors, and methods
- The first sentence should be a summary statement.
- Can use HTML tags such as
<em>...</em>
for formatting.
- For code, use
{@code ...}
so you don't have to escape <
characters.
- Place images into
doc-files
subdirectory.
Method Comments
/**
* Raises the salary of an employee.
* @param byPercent the percentage by which to raise the salary (e.g. 10 means 10%)
* @return the amount of the raise
*/
public double raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
return raise;
}
Class and Field Comments
/**
* A {@code Card} object represents a playing card, such
* as "Queen of Hearts". A card has a suit (Diamond, Heart,
* Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack,
* 12 = Queen, 13 = King)
*/
public class Card
{
/**
* The "Hearts" card suit
*/
public static final int HEARTS = 1;
...
}
Other Comments
@author
name
@version
text
@since
text
@deprecated
text
@see
reference
package.class#feature
, such as com.horstmann.corejava.Employee#raiseSalary(double)
<a href="...">...</a>
"text"
- Can include
{@link package.class#feature}
anywhere in a comment.
- Place package comments in
package-info.java
, inside /** ... */
preceding a package
statement.
- Overview comment is taken from
overview.html
.
Comment Extraction
Design classes effectively
Class Design Hints
Class Design Hints
- Break up classes that have too many responsibilities:
public class CardDeck // bad design
{
private int[] value;
private int[] suit;
...
public void shuffle() { . . . }
public int getTopValue() { . . . }
public int getTopSuit() { . . . }
public void draw() { . . . }
}
|
⇒ |
public class CardDeck
{
private Card[] cards;
...
public void shuffle() { . . . }
public Card getTop() { . . . }
public void draw() { . . . }
}
public class Card
{
private int value;
private int suit;
...
public int getValue() { . . . }
public int getSuit() { . . . }
}
|
- Make the names of your classes and methods reflect their responsibilities.
- Prefer immutable classes.