appendix a.2: review of java and object-oriented programming: part 2 “for the object-oriented...

24
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition is the class, not the algorithm.” Grady Booch

Upload: martin-andrews

Post on 25-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

Appendix A.2: Review of Java andObject-Oriented Programming: Part 2

“For the object-oriented project, remember that the primary unit of decomposition is the class, not the algorithm.”

– Grady Booch

©SoftMoore Consulting Slide 2

The Implicit Reference “this”

• Each object of a class maintains its own copy of the fields, but all objects share a single set of methods.

• ExampleBankAccount acct = new BankAccount();acct.deposit(500);

• Every method contains an implicit argument named “this” that references the object invoking the method.public void deposit(/* BankAccount this, */ int amount);

• In the definition of a method, using the name of a field references the field of the object for which the method was invoked; i.e., the object referenced by “this”

©SoftMoore Consulting Slide 3

Examples: Using the Reference “this”

• Example 1: implicit use of thispublic void deposit(int amount) { balance = balance + amount; }

• Example 2: explicit use of thispublic BankAccount(int accountId) { this.accountId = accountId; }

©SoftMoore Consulting Slide 4

Constructor this() Syntax

public class Circle { private double area = 0.0; private double radius = 0.0;

public Circle(double radius) { this.radius = radius; area = Math.PI*radius*radius; }

public Circle() { this(1.0); } ... }

Calls the first constructor

©SoftMoore Consulting Slide 5

Static Fields(a.k.a. Class Variables)

• In general, each object of a class has its own copy of the fields.

• A static field acts as a global variable for the class. There is only one copy of a static field shared by all the objects of the class (not part of each allocated object).

©SoftMoore Consulting Slide 6

Static Methods

• Analogous to static fields, a static method acts for the class as a whole and not for the individual objects of the class.– no implicit object is passed (no this reference)– can access static fields of the class– can access “normal” (non-static) fields only for objects passed

as explicit arguments– still obeys access specifiers (public, etc.)

• Static methods can be invoked like other methods using a reference to an object and the “dot” notation. They can also be invoked directly using the notationClassName.methodName()

©SoftMoore Consulting Slide 7

Example: Static Fields and Methods

public class X { // keeps track of number of objects of class X private static int objectCount = 0;

public X() { ++objectCount; } ...

/** * Returns total number of objects of class X. */ public static int getObjectCount() { return objectCount; } }

©SoftMoore Consulting Slide 8

Example: Calling Static Methods

// invoked via class XSystem.out.println(X.getObjectCount());

// invoked via an objectX x1 = new X();System.out.println(x1.getObjectCount());

Prefer the notationClassName.methodName()

when accessing static methods.

©SoftMoore Consulting Slide 9

Static Initialization Blocks

class T { static { System.out.println("Class initialization..."); ... } ... }

• Class level– designated with static modifier– block executed once when class is loaded– can be used to initialize static fields

©SoftMoore Consulting Slide 10

Generics Example

• Before Java 5 and genericsList customers = new LinkedList();...Customer c = (Customer) customers.get(0);

• Using genericsList<Customer> customers = new LinkedList<>();...Customer c = customers.get(0); // no cast necessary

©SoftMoore Consulting Slide 11

A Simple Generic Class

public class Pair<T, S> { private T first; private S second;

public Pair(T first, S second) { this.first = first; this.second = second; }

public T getFirst() { return first; }

public S getSecond() { return second; } }

©SoftMoore Consulting Slide 12

Type Variables

• A generic class or interface is declared with a type variable (often simply E) enclosed in angle brackets.

• The type variable denotes an element type that can be used within the generic class.

• A generic class can be instantiated with any class or interface typeList<BankAccount> accounts = new ArrayList<>();List<Comparable> comps = new ArrayList<>();

• A generic class cannot be instantiated with a primitive type such as int or double (use wrapper classes).

©SoftMoore Consulting Slide 13

Erasure

• Intuitively, List<String> behaves like a version of List where E has been uniformly replaced by String.

• This intuition can be helpful, but it's also misleading.

• Generics are implemented by the Java compiler as a front-end conversion called erasure.

• Erasure gets rid of (or erases) all generic type information, resulting in raw type, a list of Object. The checks for correctness and consistency are performed only by the compiler.

©SoftMoore Consulting Slide 14

Example: Pair Class After Erasure

public class Pair { private Object first; private Object second;

public Pair(Object first, Object second) { this.first = first; this.second = second; }

public Object getFirst() { return first; } public Object getSecond() { return second; } }

©SoftMoore Consulting Slide 15

The Throwable Hierarchy

An exception class is any subclass of Throwable.

Throwable

Error Exception

RuntimeException …Exception…Error

©SoftMoore Consulting Slide 16

Checked Versus Unchecked Exceptions

• Any exception that derives from class Error or class RuntimeException is called an unchecked exception.

• All other exceptions are called checked exceptions.

©SoftMoore Consulting Slide 17

Declaring Checked Exceptions

• Two special situations– you call a method that throws a checked exception– you detect an error and explicitly throw a checked exception

• The enclosing method must either handle the exception locally or it must declare the exception as part of its exception specification list.

Note that the above requirement applies onlyto checked exceptions. Unchecked exceptionsmay be declared in the exception specification

list or handled, but it is not required.

©SoftMoore Consulting Slide 18

Inheritance

• Inheritance provides the capability to create new classes from existing classes by defining only the additional facilities required by the new class.

• The new class is said to be a subclass (a.k.a. derived class) of the existing class. The existing class is said to be the superclass (a.k.a. base class) of the new class. The subclass inherits the fields and methods of its superclass.

• Classes support the concept of abstract data types (user-defined types). Inheritance extends this support to allow expression of hierarchical type/subtype relationships.

©SoftMoore Consulting Slide 19

Inheritance in Java

• Java supports single class inheritance only

• Example:public class Employee { ... }

public class Manager extends Employee { ... }

• Methods defined in the superclass can be inherited or overridden.

• Constructors are not inherited, but the constructor for the superclass can be called by the constructor for the subclass to initialize inherited fields.

Employee

Manager

©SoftMoore Consulting Slide 20

The Keyword super

• The keyword super refers to superclass of this object.

• Example: Calling a superclass methodpublic class Manager { ... String getName() { return "manager " + super.getName(); } }

• Example: Calling a superclass constructorpublic Manager(int employeeId) { super(employeeId); }

©SoftMoore Consulting Slide 21

Defining Constructors for Subclasses

• If the constructor for a subclass does not explicitly call a constructor for the superclass, then the default constructor for the superclass is called implicitly prior to the initializations defined in the subclass constructor.public class Manager extends Employee

{ public Manager() { ... // Employee() called implicitly } ...

}

• Note: If the superclass does not have a default constructor, then a superclass constructor must be called explicitly as the first statement.

©SoftMoore Consulting Slide 22

Object Type Equivalence

• Inheritance is used to represent the “is-a” relationship between classes (a Manager is an Employee).

• In general, you can use an object of a subclass in places calling for an object of its superclass without an explicit cast.Employee m = new Manager();

• An Employee is not necessarily a ManagerManager m = new Employee(); // error!

• Given an Employee, you can try to cast it to a ManagerManager m = (Manager) someEmployee;

but if it really isn't, there will be a runtime exceptionManager m = (Manager) (new Employee()); // error!

©SoftMoore Consulting Slide 23

Final Methods and Classes

• A subclass cannot override a method that has been declared as final.public final String getName() { return name; }

• A class may be declared final.– may not be extended (i.e., no subclasses)– all methods are automatically finalpublic final class Executive extends Manager { ... }

• Tradeoff: performance versus flexibility

©SoftMoore Consulting Slide 24

Polymorphism

• Calls to non-static, non-final methods are bound dynamically at run time to the appropriate method.– The method actually called is determined at runtime based on

the object referenced and not the class declared for the variable.

• The word polymorphism is Greek for “many forms.” In object-oriented programming terminology, polymorphism means that we can use a method name that is shared up and down a class hierarchy, with each class in the hierarchy implementing the action in a way appropriate to itself.

• In Java, polymorphism is implemented using non-static, non-final methods.