Jan 12, 2016
1. Everything is an object2. A program is a set of objects that
interact by sending messages (i.e. function calls)
3. Each object has its own state 4. Every object has a type (i.e. class)5. All object of the same type can
receive the same set of messages6. Every object has state, behavior,
identity
a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, and the relationships between the classes.
Examples
1. Inheritance2. Polymorphism3. Late (dynamic) binding
One form of software reuse is composition, in which a class has as members references to objects of other classes.
A class can have references to objects of other classes as members.
This is called composition and is sometimes referred to as a has-a relationship.
Date.java
(1 of 3)
1 // Fig. 8.7: Date.java
2 // Date class declaration.
3
4 public class Date
5 {
6 private int month; // 1-12
7 private int day; // 1-31 based on month
8 private int year; // any year
9
10 // constructor: call checkMonth to confirm proper value for month;
11 // call checkDay to confirm proper value for day
12 public Date( int theMonth, int theDay, int theYear )
13 {
14 month = checkMonth( theMonth ); // validate month
15 year = theYear; // could validate year
16 day = checkDay( theDay ); // validate day
17
18 System.out.printf(
19 "Date object constructor for date %s\n", this );
20 } // end Date constructor 21
Date.java
(2 of 3)
22 // utility method to confirm proper month value
23 private int checkMonth( int testMonth )
24 {
25 if ( testMonth > 0 && testMonth <= 12 ) // validate month
26 return testMonth;
27 else // month is invalid
28 {
29 System.out.printf(
30 "Invalid month (%d) set to 1.", testMonth );
31 return 1; // maintain object in consistent state
32 } // end else
33 } // end method checkMonth
34
35 // utility method to confirm proper day value based on month and year
36 private int checkDay( int testDay )
37 {
38 int daysPerMonth[] =
39 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
40
Validates month value
Validates day value
Date.java
(3 of 3)
41 // check if day in range for month
42 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
43 return testDay;
44
45 // check for leap year
46 if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
47 ( year % 4 == 0 && year % 100 != 0 ) ) )
48 return testDay;
49
50 System.out.printf( "Invalid day (%d) set to 1.", testDay );
51 return 1; // maintain object in consistent state
52 } // end method checkDay
53
54 // return a String of the form month/day/year
55 public String toString()
56 {
57 return String.format( "%d/%d/%d", month, day, year );
58 } // end method toString
59 } // end class Date
Check if the day is February 29 on a leap year
Employee.java
1 // Fig. 8.8: Employee.java
2 // Employee class with references to other objects.
3
4 public class Employee
5 {
6 private String firstName;
7 private String lastName;
8 private Date birthDate;
9 private Date hireDate;
10
11 // constructor to initialize name, birth date and hire date
12 public Employee( String first, String last, Date dateOfBirth,
13 Date dateOfHire )
14 {
15 firstName = first;
16 lastName = last;
17 birthDate = dateOfBirth;
18 hireDate = dateOfHire;
19 } // end Employee constructor
20
21 // convert Employee to String format
22 public String toString()
23 {
24 return String.format( "%s, %s Hired: %s Birthday: %s",
25 lastName, firstName, hireDate, birthDate );
26 } // end method toString
27 } // end class Employee
Employee contains references to two Date objects
Implicit calls to hireDate and birthDate’s toString methods
EmployeeTest.java
1 // Fig. 8.9: EmployeeTest.java
2 // Composition demonstration.
3
4 public class EmployeeTest
5 {
6 public static void main( String args[] )
7 {
8 Date birth = new Date( 7, 24, 1949 );
9 Date hire = new Date( 3, 12, 1988 );
10 Employee employee = new Employee( "Bob", "Blue", birth, hire );
11
12 System.out.println( employee );
13 } // end main
14 } // end class EmployeeTest Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
Create an Employee object
Display the Employee object
Inheritance provides us with a way of:◦ taking advantage of similarities between objects from different classes
◦ building new classes that are extensions of existing classes
How is a student like a person? Well, every student is a person! Students have all of the “properties” of persons,
plus some others. For example, every person has a name and an
age and so does every student. However, not every person is a student. Every student has a student id and a grade point
average, that other persons don't have.
In Java, we model a person by a Person class.
In Java, we model a student by a Student class.
Since a student is like a person with extra properties, we say the class Student is a subclass of the class Person.
We also say that Person is a superclass of Student.
In general, Person can have other subclasses as well, say Teacher. We put all the classes in an inheritance tree
with class Object as the root. We draw the tree with the root at the top.
Object
Person
Student Teacher
extends keyword a subclass inherits all of the instance
variables (and methods, except constructors) and all of the static variables (and methods) of its superclass
Singly-rooted class hierarchy◦ All classes implictly subclass java.lang.Object◦ Provides equals(), toString(), hashCode()and more basic services
No multiple inheritance
Visibility modifier, like public or private
Allows public-like access to subclasses◦ And to classes in same package
For all other classes it is like private Rationale: it’s a way to “pass over” to
subclasses some feature, without making it visible to client classes.
e.g. field enginePower in MotorVehicle◦ Makes sense to make it visible to Truck, Car
etc.
In Java, a subclass inherits all of the methods of its superclass, so they do not have to be re-implemented
However, you can also override any method if you want to
Overriding is not the same as overloading! In addition, you can add some code to an
inherited method, using the super object reference.
Costructors are NOT inherited A subclass instance includes a superclass
instance◦ Objects are constructed/initialized top-down◦ Superclass constructor must be called first
Which constructor?◦ Default superclass constructor is implicitly
called◦ If it does not exist, compiler will complain◦ If programmer wants another superclass
constructor to be called, she must specifiy that super()keyword
public class Person {// Each instance represents a Person.// Constructorspublic Person() {
// Set the name “unknown” and heightname = "unknown";Height = 160;//…
}public Person(String nameString) {
// Set the given name and heightthis( ); // do the 0 argument constructor firstthis.name = nameString;
}
public class Student extends Person {// Each instance represents a Student.public Student() {
// Set the name: "unknown", height:160, id: 0this.id = 0; // implicit call to super(); first
}public Student(String nameString) {
// Set the given name, height:160, id: 0super(nameString); // explicit callthis.id = 0;
}public Student(String nameString, int anInt) {
// Set the given name height and id,this(nameString); // or super(nameString)this.id = anInt;
}
class SuperClass {public SuperClass(String param) {
System.out.println("SuperClass constructor " + param); }}
class SubClass extends SuperClass{ public SubClass() {
System.out.println("SubClass constructor"); } public SubClass(String param) {
super(param);System.out.println("SubClass constructor " + param);
} public static void main(String args[]) {
SubClass sub = new SubClass(args[0]);}
}
Has no default constructor
Call to super() must be 1st
statement in constructor
What is going to happen?
A variable of some class can then be bound to an instance of that class or any subclass.
Any message that can be sent to an instance of a class can also be sent to an instance of its subclasses.
If the type of a method parameter or the return type of a method is a class, you can use any subclass as well.
The principle of being able to use an instance of a subclass, wherever you can use an instance of a class is called substitutability.
Person class has setName (String) method
Student class Person p = new Person (“Lin”); Student s = new Student (“Mike”, 9909); p = new student (“John”, 1230);
//p can be bounded to any kind of person p.setName(“new name”); s.setName(“new name”);
//message setName can be sent to any kind of Person
Assume that class Store has a method called register that takes a Person as a parameter:public void register(Person aPerson) {//Register the given Person as a customer.}
Store sto;//.. Some code to create stosto.register(p);sto.register(s);
Instance methods and static methods can be overridden in a subclass
Overriding methods shadow the method of the superclass
If there are multiple implementations of a method within the inheritance hierarchy of an object, the one in the “most derived” class (lowest in the tree) overrides the others, even if we refer to the object via a less derived type
Overloaded methods are selected by the compiler at compile time
Overridden methods are selected dynamically by the Virtual Machine at runtime
There is a small performance penalty to pay for dynamic binding - VM has to search for the overridden methods in subclasses.
Inheritance and Polymorphism Classic example – easy to understand All geometric shapes are types in
themselves
Suppose we’re writing a new, super-powerful drawing program
This program is so powerful, it can draw both circles and squares
And in the future – who knows! – we might be able to draw triangles, and ellipses
We define two classes, Circle and Square Each class has fields size, location, and color
Each implementation also holds an extra integer field called type, that is always set to 1 if it’s a Circle and 2 if it’s a Square
As the user draws, we save their drawing as a list of “things,” where a thing can be either a Circle or a Square
To draw things, we have to looks at the type field, and if it’s a 1 it calls method drawCircle() on the thing, and if it’s a 2 it calls drawSquare().
+ Circle() - drawCircle()
- int type = 1- long size- long color- long coordX- long coordY
Circle
+ Square() - drawSquare()
- int type = 2; - long size- long color- long coordX- long coordY
Square
We define a class Shape that has fields size, location, and color.
We define two more classes, Circle and Square
Each extends Shape In each of these two subclasses we define
a specific draw() method. Each defines its own algorithm, so Circle’s draw() draws a circle, and Square’s draw() draws a square
They override the original draw()
+ Shape()+ draw()
- long size- long color- long coordX- long coordY
Shape
+ Square()+ draw()
Square
+ Circle()+ draw()
Circle
extends
class Drawing {class Drawing {
Shape[] myShapes;Shape[] myShapes;......
public void refresh () {public void refresh () { for (int i=0;int < for (int i=0;int < myShapes.length;i++)myShapes.length;i++)
myShapes[i].draw()myShapes[i].draw() }}
}}
Both draw() methods use the size, location, and color fields, although these are not directly defined in the subclass. The fields are inherited from the superclass.
We have a list of shapes, and we ask each shape to draw itself.
NOTE: the correct method is called each time: this is polymorphism
Polymorphism seems a bit magic◦ Not only draw() of Shape is overridden …◦ … But each time the right draw() is invoked!
The code to be executed for each call is not pre-determined by the compiler◦ Early vs. late binding
Run-time language support resolves what code is to be executed each time◦ by looking at the actual type of the object
involved in the call
A cast tells the compiler to perceive an object reference as a different type
Unlike some other languages, Java performs type checking at compile-time and runtime
Casting is only legal between objects in the same inheritance hierarchy:
Can’t cast a Point to a Date, for example! a ClassCastException is thrown if you attempt to cast an object to an incompatible type at runtime
Person p = new Person( ); Student s = new Student( ); p = s ;
// legal, Substitutability rule // s = p;
// compile-time error, incompatible type p= new Student(); s = (Student) p;
// legal
Casting does not change the reference or the object being pointed to. It only changes the compiler/VM’s treatment of the reference
A common usage of Casting: When we take an Object reference out of a Container (e.g. Vector) and cast it to another type (e.g. String) we are performing a narrowing cast
Implicitly cast an object to a less derived type (i.e. a class higher up the tree)
If you have an Object that you know is of a more derived type you can downcast it ( narrow)
If you’re not sure of the type of an object, you must use instanceof before performing the cast, to avoid a ClassCastException at runtime
The instanceof operator can be used to determine the type of an object at runtime
Use it to compare an object against a particular type
Returns a boolean: ◦ true if the object is of the specified class◦ false otherwise
boolean result; String aString = “Fred”; result = (aString instanceof String); // true result = (aString instanceof Object); // true result = (aString instanceof Point); // false aString = null; result = (aString instanceof String); // false
clone() equals() finalize() toString() hashCode() notifiy()
All classes in Java inherit directly or indirectly from Object, so its 11 methods are inherited by all other classes.
Figure 9.12 summarizes Object’s methods. Can learn more about Object’s methods in the online API
documentation and in The Java Tutorial at :java.sun.com/javase-/6/docs/api/java/lang/Object.html
orjava.sun.com/docs/books/tutorial/java/IandI/ objectclass.html
Every array has an overridden clone method that copies the array. If the array stores references to objects, the objects are not copied—a
shallow copy is performed. For more information about the relationship between arrays and
class Object, see Java Language Specification, Chapter 10, at java.sun.com/docs/books/jls/third_edition/ html/arrays.html
(C) 2010 Pearson Education, Inc. All rights reserved.
(C) 2010 Pearson (C) 2010 Pearson Education, Inc. All rights Education, Inc. All rights
reserved.reserved.
(C) 2010 Pearson (C) 2010 Pearson Education, Inc. All rights Education, Inc. All rights
reserved.reserved.
(C) 2010 Pearson (C) 2010 Pearson Education, Inc. All rights Education, Inc. All rights
reserved.reserved.
Inheritance hierarchy Sometimes base class is an entity you
want to instantiate Sometimes it is just an abstract type
◦ Defines a useful set of concepts and functions but not an entity that needs instances
Example: Shape◦ You instantiate Circles, Squares etc.
abstract keyword
A class is abstract (can’t be instantiated) if:◦ Has 1 or more abstract methods◦ … or is itself declared abstract
◦ Invoking new on an abstract class makes compiler complain
Abstract methods have no code
◦ Declare an API without defining its implementation◦ Implementation is delegated to non-abstract
subclasses satisfying the same API
abstract class Shape { … }
public abstract void doSomething();
abstract class Shape{ private long color; Shape(long color) { this.color = color; } public long getColor() { return color; } ... public abstract double computeArea();}
Rectangle
baseheight
computeArea()
Circle
radius
computeArea()
Shape
colorgetColor()computeArea()
An abstract class declares an API Not “pure” API
◦ Some of the implementation is carried out there◦ Some is delegated to subclasses◦ Contract plus some content
Makes sense if some of the code logically belongs into the abstract class
Java provides means for defining pure APIs as well, called interfaces
Only contract definition ◦ abstract classes to the extreme
Create an interface like you would a class
In a file <interface_name>.java
List methods belonging to the interface
A class can then be declared to implement that interface
public interface myInf { void myMethod1(); int myMethod2(int i);}
Class myClass implements myInf { public void myMethod1() { } public int myMethod2(int i) { }}
must provide public
implementations of all myInf methods
Class access rules apply to interfaces
as well
Can subclass interfaces◦extends keyword
Can have fields in interfaces◦ They are public, static and final◦ To be immediately assigned◦ Good device for defining sets of constants◦ Refer to them as <interface_name>.<constant_name>
interface subInf extends SuperInf1, superInf2{ ... }interface subInf extends SuperInf1, superInf2{ ... }
More than just abstract classes to the extreme
While a class can extend only one class …◦ … it can implement any number of interfaces
A way around the absence of multiple inheritance in Java
Allows to assign and combine freely features and functionality to classes◦ Actually to their APIs
abstract class Bird
abstract class FlyingBird
interface CanFly
+ fly()
interface CanSwim
+ swim()class Eagle
class Penguin
extendsimplements
Interface Description
Comparable As you learned in Chapter 2, Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a class that implements the interface to be compared to one another. The interface contains one method, compareTo, that compares the object that calls the method to the object passed as an argument to the method. Classes must implement compareTo such that it returns a value indicating whether the object on which it is invoked is less than (negative integer return value), equal to (0 return value) or greater than (positive integer return value) the object passed as an argument, using any criteria specified by the programmer. For example, if class Employee implements Comparable, its compareTo method could compare Employee objects by their earnings amounts. Interface Comparable is commonly used for ordering objects in a collection such as an array. We use Comparable in Chapter 18, Generics, and Chapter 19, Collections.
Serializable A tagging interface used only to identify classes whose objects can be written to (i.e., serialized) or read from (i.e., deserialized) some type of storage (e.g., file on disk, database field) or transmitted across a network. We use Serializable in Chapter 14, Files and Streams, and Chapter 24, Networking.
Interface Description
Runnable Implemented by any class for which objects of that class should be able to execute in parallel using a technique called multithreading (discussed in Chapter 23, Multithreading). The interface contains one method, run, which describes the behavior of an object when executed.
GUI event-listener interfaces
You work with Graphical User Interfaces (GUIs) every day. For example, in your Web browser, you might type in a text field the address of a Web site to visit, or you might click a button to return to the previous site you visited. When you type a Web site address or click a button in the Web browser, the browser must respond to your interaction and perform the desired task for you. Your interaction is known as an event, and the code that the browser uses to respond to an event is known as an event handler. In Chapter 11, GUI Components: Part 1, and Chapter 22, GUI Components: Part 2, you will learn how to build Java GUIs and how to build event handlers to respond to user interactions. The event handlers are declared in classes that implement an appropriate event-listener interface. Each event listener interface specifies one or more methods that must be implemented to respond to user interactions.
SwingConstants Contains a set of constants used in GUI programming to position GUI elements on the screen. We explore GUI programming in Chapters 11 and 22.
Final keyword can be applied to prevent some of the inheritance effects
final field: i.e. constant final argument: cannot change data
within called method final method: i.e. cannot override
method in subclasses final class: i.e. cannot subclass it
◦ All of its methods are implicitly final as well
Rationale: design and/or efficiency
extends: inherit and specialize protected: share a field / method with
subclasses abstract: declare contract, delegate (part
of) implementation interface:
◦ pure API, no implementation, not even partial◦ multiple APIs ( multiple inheritance)◦ advanced type modeling
final: limits inheritance effects
OO and Java◦ OO concepts◦ Inheritance◦ Polymorphism◦ Late binding◦ Casting◦ Abstract classes◦ Interfaces