Presentation is loading. Please wait.

Presentation is loading. Please wait.

Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.

Similar presentations


Presentation on theme: "Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition."— Presentation transcript:

1 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

2 ©SoftMoore ConsultingSlide 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. Example BankAccount 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 ”

3 ©SoftMoore ConsultingSlide 3 Examples: Using the Reference “ this ” Example 1: implicit use of this public void deposit(int amount) { balance = balance + amount; } Example 2: explicit use of this public BankAccount(int accountId) { this.accountId = accountId; }

4 ©SoftMoore ConsultingSlide 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

5 ©SoftMoore ConsultingSlide 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).

6 ©SoftMoore ConsultingSlide 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 notation ClassName.methodName()

7 ©SoftMoore ConsultingSlide 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; }

8 ©SoftMoore ConsultingSlide 8 Example: Calling Static Methods // invoked via class X System.out.println(X.getObjectCount()); // invoked via an object X x1 = new X(); System.out.println(x1.getObjectCount()); Prefer the notation ClassName.methodName() when accessing static methods.

9 ©SoftMoore ConsultingSlide 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

10 ©SoftMoore ConsultingSlide 10 Generics Example Before Java 5 and generics List customers = new LinkedList();... Customer c = (Customer) customers.get(0); Using generics List customers = new LinkedList<>();... Customer c = customers.get(0); // no cast necessary

11 ©SoftMoore ConsultingSlide 11 A Simple Generic Class public class Pair { 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; } }

12 ©SoftMoore ConsultingSlide 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 type List accounts = new ArrayList<>(); List comps = new ArrayList<>(); A generic class cannot be instantiated with a primitive type such as int or double (use wrapper classes).

13 ©SoftMoore ConsultingSlide 13 Erasure Intuitively, List 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.

14 ©SoftMoore ConsultingSlide 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; } }

15 ©SoftMoore ConsultingSlide 15 The Throwable Hierarchy An exception class is any subclass of Throwable. Throwable ErrorException RuntimeException…Exception…Error

16 ©SoftMoore ConsultingSlide 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.

17 ©SoftMoore ConsultingSlide 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 only to checked exceptions. Unchecked exceptions may be declared in the exception specification list or handled, but it is not required.

18 ©SoftMoore ConsultingSlide 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.

19 ©SoftMoore ConsultingSlide 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

20 ©SoftMoore ConsultingSlide 20 The Keyword super The keyword super refers to superclass of this object. Example: Calling a superclass method public class Manager {... String getName() { return "manager " + super.getName(); } Example: Calling a superclass constructor public Manager(int employeeId) { super(employeeId); }

21 ©SoftMoore ConsultingSlide 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.

22 ©SoftMoore ConsultingSlide 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 Manager Manager m = new Employee(); // error! Given an Employee, you can try to cast it to a Manager Manager m = (Manager) someEmployee; but if it really isn't, there will be a runtime exception Manager m = (Manager) (new Employee()); // error!

23 ©SoftMoore ConsultingSlide 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 final public final class Executive extends Manager {... } Tradeoff: performance versus flexibility

24 ©SoftMoore ConsultingSlide 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.


Download ppt "Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition."

Similar presentations


Ads by Google