Review of Java and ObjectOriented Programming Part 1

Review of Java and Object-Oriented Programming: Part 1 ©Soft. Moore Consulting Slide 1

Model for Programming Real World Objects Results Problem Space Programmer’s Representation of the Problem Solution Space Software Objects Execution/ Interpretation of the Results Addition of new Solution Space Objects ©Soft. Moore Consulting Slide 2

The Class Path • CLASSPATH – environment variable specifying where the JVM should look for user-defined classes – list of directories, JAR files, and ZIP files – location of system classes is appended to the end of the list • Class path list entry separators – “: ” (colon) for Unix – “; ” (semicolon) for Windows • Example. ; C: javaclasses; C: xerces-1_4_4xerces. jar ©Soft. Moore Consulting Slide 3

Primitive Data Types • Integer Types – int – long • Floating Point Types – float • • – short – byte – double Type char Type boolean ©Soft. Moore Consulting Slide 4

Access Control • public – part of the public interface of the class – visible to any client of the class • protected – not part of the public interface of the class – visible to any subclass and any class within same package – essentially public to subclasses and classes in the same package, and private to the rest of the program • package (no explicit modifier) – visible only to classes within same package • private – visible only to enclosing class ©Soft. Moore Consulting Slide 5

Package • • Collection of classes Namespace control; e. g. , public class Test extends java. awt. Frame {. . . } or import java. awt. Frame; … public class Test extends Frame { … } • Supports data hiding – public classes are visible to code outside of package – classes with no access modifier are not visible outside the package ©Soft. Moore Consulting Slide 6

Object Variables and Reference Types • Example public class Purchase. Order { … } Purchase. Order order = new Purchase. Order(); • The variable order is a reference to the object created by new – order is not the object itself. order reference to the object ©Soft. Moore Consulting the Purchase. Order object the object Slide 7

Method Arguments • All arguments to Java methods are passed by value (copy in). Changing the formal argument does not change the actual argument. • Java passes only references to objects as method arguments, not the objects themselves. Those references are passed by value. ©Soft. Moore Consulting Slide 8

Immutable Class • A class is said to be immutable if its instances cannot be modified after construction. • Guidelines for making a class immutable – Don’t provide methods that modify the object’s state. – Ensure that the class can’t be extended (e. g. , make it final). – Make all fields private and final. • Examples in Java – String • – Wrapper classes – Big. Integer Immutable objects are simple and inherently thread-safe. “Classes should be immutable unless there is a very good reason to make them mutable” – Joshua Bloch ©Soft. Moore Consulting Slide 9

Wrapper Classes • Each Java primitive type has an equivalent class type called a “wrapper” class. – Integer – Float – Character • – – – Byte Double … The wrapper classes contain – public constants that provide attributes of the primitive type, such as MAX_VALUE and SIZE. – methods for converting to other types, such as String or int • • All wrapper class names begin with a capital letter. The wrapper classes are immutable.

Strings • Functionality is provided by standard class java. lang. String (not a primitive type). • Java strings are immutable – constant length and content. Use class java. lang. String. Buffer or class java. lang. String. Builder for mutable strings. • Examples String String • s 0 s 1 s 2 s 3 s 4 = = = new String("Hello"); "Hello"; // short-hand notation "world"; s 1 + ", " + s 2; // "Hello, world" "j" + s 1. substring(1, 5); // "jello" Prefer method equals() when comparing strings. ©Soft. Moore Consulting Slide 11

Identity versus Equality • For objects, the equality operator (==) returns true only if both variables reference the same object in memory. • Use the equals() method to test whether or not two objects contain equal values. • Examples String s 1 = "abc"; String s 2 = s 1; String s 3 = in. read. Line(); s 1 "abc" s 2 s 3 ©Soft. Moore Consulting "abc" // "abc" entered for s 3 s 1 == s 2 true s 1. equals(s 2) true s 1 == s 3 false s 1. equals(s 3) true Slide 12

Default Constructor • • A default constructor is one that has no arguments Example public class X { public X() { … } … X x 1 = new X(); ©Soft. Moore Consulting Slide 13

Copy Constructor • A copy constructor is used to initialize a newly created object with an existing object of the same class. • A copy constructor has a single argument that is a reference to an object of the same class as the constructor. • Example public class X { public X() { … } public X(X x) { … }; X x 1 = new X(); X x 2 = new X(x 1); ©Soft. Moore Consulting // default constructor // copy constructor // calls default constructor // calls copy constructor Slide 14

Conversion Constructor • A constructor that creates an object of one class and initializes it with the value of an object of a different class is sometimes referred to as a conversion constructor (converts from one class to another). • • A conversion constructor has exactly one argument Example public class Fraction { public Fraction(int n) { … } Fraction f 1 = new Fraction(5); // converts integer 5 to Fraction 5/1 ©Soft. Moore Consulting Slide 15

General Constructor • A general constructor is one that does not fit any of the other special categories. (none of the above) • Example public class Date { public Date(int year, int month, int day) { … } Date today = new Date(1993, 1, 3); • The constructor for class Date is not a default constructor, a copy constructor, or a conversion constructor. ©Soft. Moore Consulting Slide 16

Information Hiding with Java • • Fields are usually declared to be private. • Debugging benefit – all access to data is localized; any illegal value must be caused by a method. • Maintenance benefit – prevents dependencies on the underlying representation details; changes do not affect user programs. • Information hiding is enforced by the language. Access to private fields is usually restricted to an explicitly declared list of public methods. ©Soft. Moore Consulting Slide 17

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 Bank. Account acct = new Bank. Account(); acct. deposit(500); • Every method contains an implicit argument named “this” that references the object invoking the method. public void deposit(/* Bank. Account 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” ©Soft. Moore Consulting Slide 18

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 Bank. Account(int account. Id) { this. account. Id = account. Id; } ©Soft. Moore Consulting Slide 19

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; } public Circle() { this(1. 0); }. . . Calls the first constructor } ©Soft. Moore Consulting Slide 20

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). ©Soft. Moore Consulting Slide 21

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 Class. Name. method. Name() ©Soft. Moore Consulting Slide 22

Example: Static Fields and Methods public class X { // keeps track of number of objects of class X private static int object. Count = 0; public X() { ++object. Count; }. . . /** * Returns total number of objects of class X. */ public static int get. Object. Count() { return object. Count; } } ©Soft. Moore Consulting Slide 23

Example: Calling Static Methods // invoked via class X System. out. println(X. get. Object. Count()); // invoked via an object X x 1 = new X(); System. out. println(x 1. get. Object. Count()); Prefer the notation Class. Name. method. Name() when accessing static methods. ©Soft. Moore Consulting Slide 24

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 get. First() { return first; } public S get. Second() { return second; } } ©Soft. Moore Consulting Slide 25

Erasure • Intuitively, List<String> behaves like a version of List<E> where E has been uniformly replaced by String. • • This intuition can be helpful, but it's also misleading. • 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. Generics are implemented by the Java compiler as a front-end conversion called erasure. ©Soft. Moore Consulting Slide 26

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 get. First() { return first; } public Object get. Second() { return second; } } ©Soft. Moore Consulting Slide 27

The Throwable Hierarchy An exception class is any subclass of Throwable Error …Error ©Soft. Moore Consulting Exception Runtime. Exception …Exception Slide 28

Checked Versus Unchecked Exceptions • Any exception that derives from class Error or class Runtime. Exception is called an unchecked exception. • All other exceptions are called checked exceptions. ©Soft. Moore Consulting Slide 29

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. ©Soft. Moore Consulting Slide 30

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 (userdefined types). Inheritance extends this support to allow expression of hierarchical type/subtype relationships. ©Soft. Moore Consulting Slide 31

Inheritance in Java • • Java supports single class inheritance only Example: public class Employee {. . . } public class Manager extends Employee {. . . } Employee Manager • 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. ©Soft. Moore Consulting Slide 32

The Keyword super • • The keyword super refers to superclass of this object. Example: Calling a superclass method public class Manager extends Employee {. . . String get. Name() { return "manager " + super. get. Name(); } } • Example: Calling a superclass constructor public Manager(int employee. Id) { super(employee. Id); } ©Soft. Moore Consulting Slide 33

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. ©Soft. Moore Consulting Slide 34

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. ©Soft. Moore Consulting Slide 35

Abstract Classes • An abstract class is a class that is defined only for the purpose of deriving subclasses. – encapsulates commonality for all descendant classes – provides a “partial” implementation for subclasses – not intended to be used for declaring objects • An abstract method is a method signature without a corresponding body. • A class with one or more abstract methods is an abstract class. No objects can be created for an abstract class. • Any class that extends an abstract class is also abstract unless it overrides all “inherited” abstract methods. ©Soft. Moore Consulting Slide 36

Example: Abstract Class public abstract class Shape { private int x; private int y; private int width; private int height; private boolean is. Visible; public Shape() {. . . } public boolean is. Visible() { return is. Visible; } ©Soft. Moore Consulting Slide 37

Example: Abstract Class (continued) public abstract void draw(); public abstract void erase(); public void move. To(int newx, int newy) { if (is. Visible) erase(); // erase shape with old coordinates x = newx; y = newy; if (is. Visible) draw(); // redraw shape using new coordinates }. . . // other methods applicable to all shapes } ©Soft. Moore Consulting Slide 38

Using the Abstract Class Shape List<Shape> shapes = new Linked. List<Shape>(); shapes. add(new Circle(. . . )); shapes. add(new Rectangle(. . . )); . . . // add other shapes to the list for (Shape s : shapes) s. draw(); . . . for (Shape s : shapes) s. move. To(200, 200); ©Soft. Moore Consulting Slide 39

Interfaces • An interface defines a set of requirements for classes – essentially an abstract class with no methods implemented • Interfaces can contain only – public abstract methods – constants • enums • fields declared as public static final. . . • Since all methods of an interface are public and abstract, you may omit these specifiers when defining an interface. • An interface may be thought of as a role played by objects of classes that implement the interface. ©Soft. Moore Consulting Slide 40

Interfaces (continued) • Example public interface Comparable<T> { int compare. To(T other); } • An interface may have additional requirements explained in the comments; e. g. , (e 1. compare. To((Object)e 2) == 0) must have the same boolean value as e 1. equals((Object)e 2) • A class can only extend one superclass, but it can implement multiple interfaces. ©Soft. Moore Consulting Slide 41

Implementing an Interface • To make a class implement an interface 1. Declare that the class implements the interface 2. Provide definitions for all methods in the interface. • Example (uses compare. To() from class String) public class Employee implements Comparable<Employee> {. . . public int compare. To(Employee other) { if (last. Name. equals(other. last. Name)) return first. Name. compare. To(other. first. Name) else return last. Name. compare. To(other. last. Name) } } ©Soft. Moore Consulting Slide 42
![Using an Interface public static void insertion. Sort(Comparable a[]) { int j; Comparable save; Using an Interface public static void insertion. Sort(Comparable a[]) { int j; Comparable save;](http://slidetodoc.com/presentation_image_h2/99f254be13df1fd83ff7cd69d74ee347/image-43.jpg)
Using an Interface public static void insertion. Sort(Comparable a[]) { int j; Comparable save; for (int i = 1; i < a. length; ++i) { // insert a[i] into the sorted slice a[0]. . a[i - 1] save = a[i]; j = i - 1; while (j >= 0 && save. compare. To(a[j]) < 0) { a[j + 1] = a[j]; --j; } a[j + 1] = save; // insert saved A[i] } } ©Soft. Moore Consulting Slide 43

Interfaces versus Classes An interface is similar to a class, but there are several important differences: • All methods in an interface type are abstract; they don't have an implementation. • • • All methods in an interface type are automatically public. An interface type does not have instance fields. A class can extend only one existing class (single inheritance), but it can implement multiple interfaces. ©Soft. Moore Consulting Slide 44

Class Object (The Mother of all Classes) • • Any class without an explicit superclass extends Object Selected methods from class Object clone() boolean equals(Object obj) void finalize() Class<? extends Object> get. Class() int hash. Code() String to. String() plus several methods related to threads ©Soft. Moore Consulting Slide 45

The equals() Method • The equals() method in class Object tests for equality of object references. – not usually the desired semantics for application classes – consider overriding • Requirements – reflexive: x. equals(x) should be true for any non-null x – symmetric: x. equals(y) should be true if and only if y. equals(x) is true – transitive: if x. equals(y) and y. equals(z) are both true, then x. equals(z) should be true – consistent: if x and y have not changed, then repeated calls to x. equals(y) should return the same value – if x is not null, then x. equals(null) should return false ©Soft. Moore Consulting Slide 46

The hash. Code() Method • A hash code is an integer derived from an object. – can be negative – used for “hash” based collection classes • Should “scramble” objects: If x and y are distinct objects, then there should be a high probability that x. hash. Code() and y. hash. Code() are different. • The default hash code inherited from Object is based on an object’s address in memory. • If you override equals(), you should also override hash. Code() to make the methods compatible If x. equals(y) is true, then x. hash. Code() == y. hash. Code() must also be true. ©Soft. Moore Consulting Slide 47
- Slides: 47