Java OOp
Java OOp
Everything is an object
2. 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 messages
6. 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. Inheritance
2. Polymorphism
3. 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
7 { ava
8 Date birth = new Date( 7, 24, 1949 ); Create an Employee object
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 Display the Employee object
14 } // end class EmployeeTest
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.
// Constructors
public Person() {
// Set the name “unknown” and height
name = "unknown";
Height = 160;
//…
}
public Person(String nameString) {
// Set the given name and height
this( ); // do the 0 argument constructor first
this.name = nameString;
}
public class Student extends Person {
// Each instance represents a Student.
public Student() {
// Set the name: "unknown", height:160, id: 0
this.id = 0; // implicit call to super(); first
}
public Student(String nameString) {
// Set the given name, height:160, id: 0
super(nameString); // explicit call
this.id = 0;
}
public Student(String nameString, int anInt) {
// Set the given name height and id,
this(nameString); // or super(nameString)
this.id = anInt;
}
Has no default
constructor
class SuperClass {
public SuperClass(String param) {
System.out.println("SuperClass constructor " + param);
}
} Call to super()
must be 1st
class SubClass extends SuperClass{
public SubClass() {
statement in
constructor
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]);
}
}
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 sto
sto.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
themselves
Suppose we’re writing a new, super-
powerful drawing program
This program is so powerful, it can draw
- drawCircle() - drawSquare()
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()
class Drawing {
Shape
- long size Shape[] myShapes;
- long color ...
- long coordX public void refresh () {
- long coordY for (int i=0;int <
myShapes.length;i++)
+ Shape()
+ draw() myShapes[i].draw()
}
}
extends
Circle Square
+ Circle() + Square()
+ draw() + 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
abstract
◦ Invoking new on anclass Shape
abstract { … }
class makes compiler
complain
Abstract methods have no code
public abstract void doSomething();
◦ Declare an API without defining its implementation
◦ Implementation is delegated to non-abstract
subclasses satisfying the same API
abstract class Shape{
private long color;
Shape(long color) {
this.color = color;
}
public long getColor() {
return color;
}
...
public abstract double computeArea();
}
Shape
color
getColor()
computeArea()
Rectangle Circle
base radius
height
computeArea() 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
extends
implements
abstract class FlyingBird
interface CanSwim
+ swim()
class Eagle
class Penguin
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 You work with Graphical User Interfaces (GUIs) every day. For example, in your
interfaces 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