You are on page 1of 48

Java Programming

Java Class Design

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Overview
This lesson covers the following topics:
Model business problems using Java classes
Make classes immutable
Compare access levels default and public
Use the instanceof operator to compare object types
Use virtual method invocation
Use upward and downward casts

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Classes
A Java class is a template that defines the features of one
or more objects.
A class can be thought of as a category used to define
groups of things.
Classes:
Define and implement methods.
Implement methods from implemented interfaces.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

What Classes Can and Cannot Do


Classes can:
Declare constants and variables.
Inherit methods from another class.
Define and implement methods.
Override inherited methods when the method is public or
protected.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

What Classes Can and Cannot Do (cont.)


Classes can:
Be instantiated by:
A public or protected constructor.
A public or protected static method or nested class.
Classes cannot:

Override inherited methods when the method is final.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

When Classes Can be Subclassed or Made


Immutable
A class can be subclassed when:
The class is not declared final.
The methods are public or protected.
A class can be immutable by:
Making it final.
Limiting instantiation to the class constructors.
Eliminating any methods that change instance variables.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

super() Method Call


The super() method call lets you call the parent class in a
class hierarchy. In this case, the static nested class
extends the behavior of the containing class.
The static nested class also provides the means for
instantiating a containing class when its constructor is
configured as private access. This is the second way to
instantiate a class that has a restricted or private access
qualifier for its class constructors.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Interface
An interface is a Java construct that helps define the roles
that an object can assume. It is implemented by a class or
extended by another interface.
Interfaces define collections of related methods without
implementations.
All methods in a Java interface are abstract.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Possibilities of Interfaces
Interfaces give developers two possibilities:
They can develop a concrete class that just implements
the interface and then use that class by creating a
variable of that type.
This means the class that is a copy of the class and has its
behaviors through aggregation.
Aggregation is simply the process of gaining access to the
behaviors of an object type when you declare a variable of
that type in a class.

They can develop a concrete class that implements one


or many interfaces.
9

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

What An Interface Can Do


An interface:
Can declare public constants.
Defines methods without implementation.
Can only refer to its constants and defined methods.
Can be used with the instanceof operator.

10

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

What An Interface Can Do (cont.)


While a class can only inherit a single superclass, a class
can implement more than one interface.
public class className implements interfaceName{
...class implementation...}

Implement is a keyword in Java that is used when a class inherits


an interface.

11

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Interface Method
An interface method:
In an interface, each method is public even when you
forget to declare it as public.
Is implicitly abstract but you can also use the abstract
keyword.

12

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Declaring an Interface
To declare a class as interface you must replace the
keyword class with the keyword interface.
This will declare your interface and force all methods to be
abstract and make the default access modifier public.
Replace class with interface.
public interface Chassis
{
public final String chassis = "Generic";
... public Chassis getChassisType();
public void setChassisType(String vehicleFrameType);}

13

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Chassis Example 1
Classes that extend Chassis
will have to provide working
methods for methods defined
here.

public interface Chassis


{
public final String chassis = "Generic";
... public Chassis getChassisType();
public void setChassisType(String vehicleFrameType);}

Class implementing the Chassis interface:


public class VehicleChassis implements Chassis {
private String chassisName;
public VehicleChassis() {
this.chassisName = Chassis.chassis; }

Classes implementing an
interface can access the
interface constants.
14

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Chassis Example 1 Explained


The keyword final means that the variable chassis is a
constant in the interface because you can only define
constants and method stubs in an interface.
this.chassisName = Chassis.chassis;

The assignment of the constant from an interface uses the


same syntax that you use when assigning a static variable
to another variable.

15

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Chassis Example 2
Implementing classes must
public interface Chassis
{
provide the working method.
public final String chassis = "Generic";
... public Chassis getChassisType();
public void setChassisType(String vehicleFrameType);}

Class implementing the Chassis interface methods:


public Chassis getChassisType() {
return this; }
public void setChassisType(String vehicleChassis) {
this.chassisName = vehicleChassis; }

Classes using an interface


must provide
implementation for all
methods.
16

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Class Implements Interface: Steps 1-3


The steps to implementing an interface are shown in the
example below and on the next few slides.
public class ManufacturedEngine implements Engine {
...
String
Date
...

engineManufacturer;
engineManufacturedDate;

Step 1: Implements Engine


interface as a Concrete
ManufacturedEngine class.
Step 2: Declare local
variables for the
ManufacturedEngine class.

public ManufacturedEngine() {
this.engineManufacturer = "Generic";
this.engineManufacturedDate = new Date();
this.engineMake = "Generic";
this.engineModel = "Generic";
... }
17

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Step 3: Create a default


constructor that assigns
default values to all instance
variables.

Java Class Design

Class Implements Interface: Steps 4-5

Step 4: Declare overloaded


constructor.
public class ManufacturedEngine implements Engine {
...
public ManufacturedEngine(
String engineManufacturer
, Date engineManufacturedDate
, String engineMake
Step 5: Assign call
, String engineModel
parameters to local instance
, DriveTrain driveTrain
variables.
, int engineCylinders
, Fuel engineType ) {
this.engineManufacturer = engineManufacturer;
this.engineManufacturedDate = engineManufacturedDate;
this.engineMake = engineMake;
this.engineModel = engineModel;
... }
18

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Class Implements Interface: Step 6

public class ManufacturedEngine implements Engine {

Step 6: Implement final methods for all methods in


the interface, which makes them non-subclassable.
...
public final void setEngineManufacturedDate(
Date manufacturedDate) {
this.engineManufacturedDate = manufacturedDate; }
public final void setEngineManufacturer(
String manufacturer) {
this.engineManufacturer = manufacturer; }
public void setEngineMake(String engineMake) {
this.engineMake = engineMake; }
...

19

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Class Implements Interface: Step 7-12


Step 7: Implements Engine interface a Vehicle class.
public class Vehicle implements Engine {
...

Step 8: Declare an instance


variable using Engine interface.

private Engine vehicleEngine;


...
this.vehicleEngine = new ManufacturedEngine();
...

Step 9: Create a default


instance of a class that
implements only the Engine
interface inside the Vehicle
constructor.

Step 10: Final prevents subclassing of the method.

public final void setEngineManufacturedDate(


Date manufacturedDate) {
vehicleEngine.setEngineManufacturedDate(
manufacturedDate);
...

Step 11: Implement


methods from the
Engine interface.

Step 12: Call the implementation of the interface method from


the ManufacturedEngine because you can't call it from the
Engine interface and the methods can't be subclassed.

20

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Why Use an Interface?


You may be wondering why you would ever want to create
a class that has no implementation.
One reason could be to force all classes that implement
the interface to have specific qualities.

21

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Store Example
A store owner wants to create a website that displays all
items in the store. We know:
Each item has a name.
Each item has a price.
Each item is organized by department.
It would be in the store owner's best interest to create an
interface for what defines an item. This will serve as the
blueprints for all items in the store, requiring all items to at
least have the defined qualities above.
22

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Adding a New Item to Store Example


The owner adds a new item to his store named cookie:
Each costs 1 US dollar.
Cookies can be found in the Bakery department.
Each cookie is identified by a type.
The owner may create a Cookie class that implements the
Item interface such as shown to the right, adding a
method or two that is specific to cookie items.

23

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Create Cookie Class


The owner may create a Cookie class that implements the
Item interface, such as shown below, adding a method or
two specific to cookie items.
public class Cookie implements Item{
public String cookieType;
private int price;
public Cookie(String type){
cookieType = type;
price = 1;
}
public String getItemName()
{return Cookie;}
public int getPrice()
{return price;}
public void setPrice(int price)
{this.price = price};
public String getDepartment()
{return Bakery;}
public String getType()
{return type;}
}
24

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Add Chocolate Chip Cookies to Store


The owner wants to add Chocolate Chip Cookies to his
online store. He would create a cookie such as shown
below:
Cookie chocChip = new Cookie(Chocolate Chip);

He can use the Item interface in a similar way with all of


the other items in his store to assure that every item has
the qualities that makes it an item.
This will help him as he creates his online store, by
allowing for things such as searching items by
departments or by price.
25

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Abstract Classes
An abstract class provides a base class from which other
classes extend.

Abstract classes can provide:


Implemented methods: Those that are fully implemented
and their child classes may use some.
Abstract methods: Those that have no implementation and
require child classes to implement them.

Abstract classes do not allow construction directly but


you can create subclasses or static nested classes to
instantiate them.

26

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Abstract Classes (cont.)


An abstract class:
Must be defined by using the abstract keyword.
Cannot be instantiated into objects.
Can have local declared variables.
Can have method definitions and implementations.
Must be subclassed rather than implemented.

27

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Abstract Classes (cont.)


An instance can be created by:
Using a static method inside the abstract class to return
an instance of the class.
Using a static nested class inside the abstract class.

28

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

More Information about Abstract Classes


If a concrete class uses an abstract class, it must inherit it.
Inheritance precludes inheriting from another class. As a
rule, interfaces are superior solutions to abstract classes.
Abstract classes are important when all derived classes
should share certain methods.
The alternative is to use an interface, then define at least
one concrete class that implements the interface.
This means you can use the concrete class as an object
type for a variable in any number of programs which
provides much greater flexibility.
29

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Abstract Class Code


public abstract class Chassis
{
public final String chassis = "Generic";
...
public abstract Chassis getChassisType();
public abstract void setChassisType(
String vehicleFrameType);}

Implementing classes must


provide the working
method for abstract
classes.

Class implementing the Chassis interface methods:


public Chassis getChassisType() {
return this; }
public void setChassisType(String vehicleChassis) {
this.chassisName = vehicleChassis; }

Classes using an abstract class


must provide implementation for all
methods.
30

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Immutable Classes
Immutable classes:
Make the class final, which means that other classes
can't extend its behavior.
Only allow instance variable assignments in the default
or overloaded constructor.
...
public final class Car extends Vehicle {
...

31

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

The instanceof Operator


The instanceof operator allows you determine the type of
an object. It takes an object on the left side of the operator
and a type on the right side of the operator and returns a
boolean value indicating whether the object belongs to
that type or not.
For example:
(String instanceof Object) would return true.
(String instanceof Integer) would return false.

32

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Using the instanceof Operator


This could be useful when you desire to have different
object types call methods specific to their type. In this
code, Feature is an interface and InteriorFeature and
ExteriorFeature both extend Feature.
public final class Car extends Vehicle {
private Feature[] feature = new Feature[10];
...
public Car() {
Super(); ...
Feature[] f =
{ new InteriorFeature("No Interior Features")
, new ExteriorFeature("No Exterior Features")};
this.feature = f;
...

33

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

The InteriorFeature and


ExteriorFeature are instances
of concrete classes that
implement the Feature
interface.

Java Class Design

instanceof Operator Example


In this example, the instanceof operator is used to find all
of the exterior features in an array and add them to a
String called list.
...
public String getExteriorFeatures() {
String list = "";
for (int i = 0; i < this.feature.length; i++) {
if (this.feature[i] instanceof ExteriorFeature)
if (list.length() == 0) {
list += this.feature[i]; }
else {
list += ", " + this.feature[i]; }}}
return list; }
...

34

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

instanceof Operator Example Explained


In the previous instanceof operator example:
The array is defined using the Feature interface. It can
hold any class that solely implements its methods and
extends them with other specialization methods and
variables.
As the program reads through the array, it assigns the
string value from the toString() method to the list
variable.
You should always consider overridding the toString(),
hash(), and equals() methods in your user-defined
classes.
35

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Virtual Method Invocation


Virtual method invocation is the process where Java
identifies the type of subclass and calls its implementation
of a method.
When the Java virtual machine invokes a class method, it
selects the method to invoke based on the type of the
object reference, which is always known at compile time.

36

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Virtual Method Invocation (cont.)


On the other hand, when the virtual machine invokes an
instance method, it selects the method to invoke based on
the actual class of the object, which may only be known at
runtime.

37

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Virtual Method Invocation Example

...
public String toString() {
String list = "";
for (int i = 0; i < this.feature.length; i++) {
if (list.length() == 0) {
list += this.feature[i]; }
else {
list += "\n
: " +this.feature[i];}
}
return super.toString() + "\n" +
"Features
: " + list + "\n" +
"Car Axle
: " + carAxle; }
...

38

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Assigning the object


to the String calls that
object's toString
method.

Java Class Design

Virtual Method Invocation Example Explained


The toString() method uses virtual method invocation by
calling the toString() method of the different subclasses.
The decision is made by JVM to call the toString method
implemented in the subclasses rather than the toString
method in the superclass or the Object class.
One prints External before the feature and the other
prints Internal before the feature.

39

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Upcasting and Downcasting


Casting is the principal of changing the object type during
assignment.
Upcasting loses access to specialized methods in the
subclassed object instance.
Downcasting gains access to specialized methods of the
subclass.

40

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Upcasting and Downcasting Example


Casting objects works somewhat like casting primitives.
For example, when downcasting a double to an int, the
values to the right of the decimal point are lost. This is a
loss of precision.
For that reason, you must explicitly specify the downcast
type. For example:
double complexNumber = 45.75L;
int simpleNumber = 34;
simpleNumber = (int) complexNumber;

41

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Upcasting and Downcasting Example (cont.)


Upcasting does not risk the loss of precision nor require
you to specify the new data type in parentheses.

42

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Upcasting Example
Even though vehicle is a Car, it was upcast to Vehicle so it
lost access to its Car-specific methods and fields.
Attempts to access subclass methods fail at compile time.
Vehicle is a superclass.
Car is a subclass of Vehicle.

...
Vehicle vehicle =
(Vehicle) new Car("Honda",new Date(1325599999999L)
,"Honda","Prelude","Coupe"
, new VehicleChassis("Unibody")
, new ManufacturedEngine("Honda"
, new Date(), "H-Series","H23A1"
, DriveTrain.TWO_WHEEL_DRIVE,4
, Fuel.MIDGRADE_GASOLINE),f,2);
...
Fails because the method belongs to
vehicle.getExternalFeatures();
the Car subclass and access to it is
...

lost when upward casting.


43

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Upcasting Example Explained


The loss of precision in object assignments differs from
primitive data types. Upcasting from a specialized
subclass to a generalized superclass loses access to the
specialized variables and methods.
Car is a subclass of Vehicle.

...
Vehicle vehicle =
(Vehicle) new Car("Honda",new Date(1325599999999L)
,"Honda","Prelude","Coupe"
Vehicle is a superclass.
, new VehicleChassis("Unibody")
, new ManufacturedEngine("Honda"
, new Date(), "H-Series","H23A1"
, DriveTrain.TWO_WHEEL_DRIVE,4
, Fuel.MIDGRADE_GASOLINE),f,2);
...
Fails because the method belongs to
vehicle.getExternalFeatures();
the Car subclass and access to it is
...

lost when upward casting.


44

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Downcasting Example
Downcasting the superclass works here because the
runtime object is actually a Car instance. The Vehicle
instance is first cast to a subclass of itself before running
the Car instance method.
Vehicle is a superclass.
...
Car is a subclass of Vehicle.
Vehicle vehicle =
(Vehicle) new Car("Honda",new Date(1325599999999L)
,"Honda","Prelude","Coupe"
, new VehicleChassis("Unibody")
, new ManufacturedEngine("Honda"
, new Date(), "H-Series","H23A1"
, DriveTrain.TWO_WHEEL_DRIVE,4
, Fuel.MIDGRADE_GASOLINE),f,2);
...
Succeeds because the
((Car) vehicle).getExternalFeatures();
method belongs to the Car
...

subclass.
45

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Downcasting Example Explained


Downcasting from a generalized to specialized subclass
returns access to the specialized variables and methods if
they were there from a previous upcast.
Vehicle is a superclass.
...
Car is a subclass of Vehicle.
Vehicle vehicle =
(Vehicle) new Car("Honda",new Date(1325599999999L)
,"Honda","Prelude","Coupe"
, new VehicleChassis("Unibody")
, new ManufacturedEngine("Honda"
, new Date(), "H-Series","H23A1"
, DriveTrain.TWO_WHEEL_DRIVE,4
, Fuel.MIDGRADE_GASOLINE),f,2);
...
Succeeds because the
((Car) vehicle).getExternalFeatures();
method belongs to the Car
...

subclass.
46

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Terminology
Key terms used in this lesson included:
Abstract class
Abstract constructor
Casting
Downward cast
Immutable classes
instanceof
Interface
Upward cast
Virtual method invocation
47

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Java Class Design

Summary
In this lesson, you should have learned how to:
Model business problems using Java classes
Make classes immutable
Compare access levels default and public
Use the instanceof operator to compare object types
Use virtual method invocation
Use upward and downward casts

48

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

You might also like