Programming in Java: OOP, Object, Class
Programming in Java: OOP, Object, Class
: /
56
Java OOP-class
Class elements
57
Java OOP-class
Constructors
For purpose of initialization objects have special
methods called constructors.
To write a constructor you must adhere to two rules :
1. The method name must exactly match the class
name.
2. There must not be a return type declared for the
method.
Java has NO destructor.
58
Java OOP-class
The Default Constructor
Every class has a constructor.
If you dont write one Java provides one for you. This
constructor takes no arguments and has an empty body.
? What If you write one constructor ?
59
Java OOP-class
Struct in C/C++
#include <stdio.h>
struct Student {
long sid;
char name[9]; /* Big5 */
float score[13]; /* 13 */
}; /* */
int main( ) {
struct Student x; /* C++ C99 struct */
x.sid = 123;
strcpy(x.name, "") ; /* */
/* loop x.score[?] */
}
Why using struct ?
Java has no struct
60
Java OOP-class
Struct vs. Class in C++ (1/2)
#include <iostream.h>
class Student { // struct Student { ?
long sid;
};
int main( ) {
Student x;
x.sid = 123; // compile, access not allowed
cout << "== " << x.sid << endl; // compile
return 0;
}
private
61
Java OOP-class
Struct vs. Class in C++ (2/2)
#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
};
int main( ) {
Student x, y;
x.setId(123); // OK, public function setId( )
cout << " == " << x.showNumber( ) << endl; // OK
return 0;
}
62
Java OOP-class
Class(Object) Constructor 1/4 (C++)
#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
};
int main( ) {
Student x, m, n;
Student y(456); // Error
x.setId(123);
return 0;
}
Student y(456) ; !
default constructor
default constructor
63
Java OOP-class
Class(Object) Constructor 2/4 (C++)
#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
Student(long x) { sid = x; }
};
int main( ) {
Student x; // Error
Student y(456); // OK now
x.setId(123);
return 0;
}
Student y(456) ; OK
constructor
Student x; !
default constructor
:
64
Java OOP-class
#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long x) { sid = x; }
Student(long x=0) { sid = x; }
};
int main( ) {
Student x, y(456); // OK
x.setId(123);
return 0;
}
Student x;
Default
Class(Object) Constructor 3/4 (C++)
65
Java OOP-class
#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
Student(long x) { sid = x; cout << "Hehehe\n"; }
Student( ) { sid=0; cout << "Haha\n"; }
};
int main( ) {
Student x, y(456); // OK
x.setId(123);
return 0;
}
Student x;
constructor
Class(Object) Constructor 4/4 (C++)
66
Java OOP-class
More about Classes
Properties:
Single implementation inheritance - extends
The inherited class is called superclass.
Multiple interface inheritance - implements
All classes inherit from java.lang.Object
Scope: (next slide)
67
Java OOP-class
Scope
68
Java OOP-class
The Life Cycle of an Object Creation (I)
Creating Objects
Rectangle rect = new Rectangle();
Declaring an Object
Object declarations can also appear alone :
Rectangle rect;
In Java, classes and interfaces can be used as data types.
Declarations do not create new objects.
Instantiating an Object
The new operator allocates memory for a new object.
The new operator requires a argument: a call to a constructor.
The new operator creates the object, and the constructor initializes it.
new Rectangle(100, 200);
The new operator returns a reference to the newly created object.
Rectangle rect = new Rectangle(100,200);
After this statement, rect refers to a Rectangle object.
69
Java OOP-class
The Life Cycle of an Object -- Creation (II)
Initializing an Object
Constructors have the same name as the class and have no return
type.
public Rectangle(Point p)
public Rectangle(int w, int h)
public Rectangle(Point p, int w, int h)
public Rectangle()
Example:
Rectangle rect = new Rectangle(100, 200);
Rectangle rect = new Rectangle(
new Point(44,78));
A constructor can takes no arguments, is called a no-argument
constructor.
If a class does not define any constructors, Java provides a no-
argument constructor, called the default constructor.
70
Java OOP-class
The Life Cycle of an Object -- Access
Using Objects
Referencing an Object's Variables
objectReference.variable
Example:
int areaOfRectangle = rect.height * rect.width;
Calling an Object's Methods
objectReference.methodName(); or
objectReference.methodName(argumentList);
Example:
rect.move(15, 37);
int areaOfRectangle =
new Rectangle(100, 50).area();
71
Java OOP-class
The Life Cycle of an Object Cleanup
Cleaning Up Unused Objects
An object is eligible for garbage collection when there are no more
references to that object.
The Garbage Collector
Automatically frees an object, if not referenced.
prevents memory leaks
claimed delay ~200ms for 4MB
Mark-sweep garbage collector
The garbage collector runs in a low-priority thread.
When the system runs out of memory.
In response to a request from a Java program.
When the system is idle.
72
Java OOP-class
Finalization
When freeing an object, the system will call this first.
The finalize method is a member of the Object class.
Implementing a finalize method to release resources that
aren't under the control of the garbage collector, such as native
peers.
Scenario: For a file object, when freed, need to close it.
Problem: Make the internal JVM implementation for
memory management very complicated.
Example
public class Rectangle {
public Point origin;
. . .
protected void finalize() throws Throwable {
origin = null;
super.finalize();
}
}
73
Java OOP-class
Example for Overriding (1/2)
class Point {
protected int x,y;
Point(int x, int y) {this.x = x; this.y = y;}
void draw(){
System.out.println(Point at+x+,+y);
};
}
Subclassing:
class Cpoint extends Point{
private Color c;
Cpoint(int i, int j, Color c){
super(i,j);
this.c =c;
};
void draw(){
System.out.println(Color Point at + i + , + j + , + c);
};
}
74
Java OOP-class
Example for Overriding (2/2)
class PointApp{
public static void main(){
Point p = new Point(5,5);
Cpoint cp = new Cpoint(1,1,Red);
p.draw();
cp.draw();
p = cp;
p.draw();
// call Points draw() or Cpoints draw()?
}
}
Overriding overloading !
75
Java OOP-class
Overloading
A Method's Name (function name)
Java supports method name overloading so that multiple methods can
share the same name.
class DataRenderer {
void draw(String s) { . . . }
void draw(int i) { . . . }
void draw(float f) { . . . }
}
Overloaded methods are differentiated by the number and type of the
arguments.
A subclass may override a method in its superclass.
The overriding method must have the same name, return type, and parameter
list as the method it overrides.
Java operator overloading
76
Java OOP-class
Abstract Classes in Java
Abstract classes created using the abstract keyword:
public abstract class MotorVehicle { }
In an abstract class, several abstract methods are declared.
- An abstract method is not implemented in the class, only declared. The
body of the method is then implemented in subclass.
- An abstract method is decorated with an extra abstract keyword.
Abstract classes can not be instantiated! So the following is
illegal:
MotorVehicle m = new MotorVehicle; // !
//
//
77
Java OOP-class
Abstract methods
Abstract methods are declared but do not contain an
implementation.
For example, the MotorVehicle class may have an abstract
method gas( ):
public abstract class MotorVehicle {
private double speed, maxSpeed;
void accToMax( ) { speed = maxSpeed;} //!
public abstract void gas( ); // ; C++ =0;
/* */
}
So MotorVehicle can NOT be instantiated
(ie., can not be used to create an object.)
78
Java OOP-class
Example of Abstract Classes (1/2)
Example:
abstract class Stack {
abstract void push(Object o);
abstract Object pop();
}
public class ArrayStack extends Stack {
.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}
class LinkedStack extends Stack {
.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}
79
Java OOP-class
Example of Abstract Classes (2/2)
// ============================== Another file
...
static public int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...
80
Java OOP-class
Interfaces
Defines a set of methods that a class must implement
An interface is like a class with nothing but abstract methods
and final and static fields (constants).
An interface can also have fields, but the fields must be
declared as final and static.
All methods are abstract implicitly.
Interface can be added to a class that is already a subclass of
another class. (implements)
To declare an interface:
public interface ImportTax {
public double calculateTax( );
}
81
Java OOP-class
Example of Interfaces (1/2)
interface Stack {
void push(Object o);
Object pop();
}
public class ArrayStack implements Stack {
.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}
class LinkedStack implements Stack {
.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}
82
Java OOP-class
Example of Interfaces (2/2)
//============================== Another file
...
static public int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...
83
Java OOP-class
Difference between Abstract Class and Interface
An abstract class is a class containing several abstract methods.
Each abstract method is prefixed with the keyword abstract.
An abstract class can not be instantiated but can be extended
(subclassed).
An interface contains only abstract methods and constants.
Each abstract method is not prefixed with the keyword
abstract.
An interface can only be implemented.
84
Java OOP-class
How C++ Deals with Interfaces
or Abstract Classes
Use virtual functions:
class Stack {
virtual void push(void* o) = NULL;
virtual void* pop() = NULL; // NULL 0
}
// C++ virtual = NULL; = 0;
// = NULL; =0; virtual functionpure virtual function
// Java virtual
What are the internal designs?
Key for the designs of COM/DCOM (MicroSoft)
85
Java OOP-class
Example for C++
class ArrayStack : Stack {
.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}
class LinkedStack : Stack {
.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}
============================== Another file
...
int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...
86
Java OOP-class
Packages and Library
Organize class name space
Hierarchical division must be reflected in directory structure, i.e.,
package cyc.sys;
import java.io.*;
class Login { /* in fact, this is cyc.sys.Login */ }
Default packages (library) -- JDK
java.lang - Object, Thread, Exception, String,...
java.io - InputStream, OutputStream, ...
java.net - Networking
support for Socket & URL-based objects
java.awt - Abstract window toolkit
defines a simple, restricted windowing API
java.util - Hashtable, Vector, BitSet, Regexp, ..
java.tools - Compilation, Debugging, Documentation
87
Java OOP-class
Naming a Package
The name of the Rectangle class in the graphics package
is really graphics.Rectangle
The name of the Rectangle class in the java.awt package
is really java.awt.Rectangle
Convention
com.company.package
com.company.region.package
Java graphics.Rectangle
88
Java OOP-class
Access Modifiers
(no keyword): class/package access (different from C++)
I.e., package available
public: world access (same as C++)
private: class access (same as C++)
protected: subclassing access(same as C++)
static: only one copy for all instances
abstract: left unimplemented
final: not overridden
native: methods implemented in native code.
synchronized: described in Thread
transient: data that is not persistent
89
Java OOP-class
Comparisons
Controlling Access to Members of a Class
Specifier Class Subclass Package World
private X
protected X X X
public X X X X
package X X
X !
90
Java OOP-class
Static
static:
only one copy for the class and all instances
Usually used as a global variable (even no instances)
class TestStatic {
int x, y, z;
int average() {return (x+y+z)/3; }
static int j = 0;
static int peek() {
j += 2;
x = 3; // error!
}
static int k = peek();
static { j = j*5; } // done when loading class
public static void main(String[] args) {
...
TestStatic ts = new TestStatic();
int ave = ts.average();
...
}
}
Static method
Static block
Static variable j,k
Static
method
91
Java OOP-class
Final
Final variables:
The value of a final variable cannot change after it has been
initialized.
Such variables are similar to constants in other programming
languages.
final Color red = Color.red;
A final local variable that has been declared but not yet initialized is
called a blank final.
final int blankfinal;
. . .
blankfinal = 0;
Final methods: methods that cannot be overridden.
Prevent clients from overriding.
Allow for JIT to optimize.
92
Java OOP-class
Transient vs. Volatile
transient : used in object serialization to mark member
variables that should not be serialized.
volatile : used to prevent the compiler from
performing certain optimizations on a member.
93
Java OOP-class
Nested Class
A nested class is a class that is a member of another class.
class EnclosingClass{
. . .
class ANestedClass {
. . .
}
}
Define a class within another class when the nested class
makes sense only in the context of its enclosing class.
For example, a text cursor makes sense only in the context of a
particular text component.
A nested class has a special privilege:
It has unlimited access to its enclosing class's members, even for
private.
Just like a method that can access private.
94
Java OOP-class
Types of Nested Class
class EnclosingClass{
. . .
static class AStaticNestedClass {
. . .
}
class InnerClass {
. . . /* static is wrong in this inner class */
}
}
A static nested class is called: a static nested class.
A static nested class cannot refer directly to instance variables or
methods defined in its enclosing class
A nonstatic nested class is called an inner class.
An inner class is associated with an instance of its enclosing class and
has direct access to that object's instance variables and methods.
Because an inner class is associated with an instance, it cannot define
any static members itself.
95
Java OOP-class
Nested vs. Inner
To help differentiate the terms nested class and inner class:
The term "nested class" reflects the syntactic relationship between
two classes.
In contrast, the term "inner class" reflects the relationship between
instances of the two classes.
An instance of InnerClass can exist only within an instance of
EnclosingClass,
It has direct access to instance variables and methods of its enclosing
instance.
class EnclosingClass {
. . .
class InnerClass {
. . .
}
}
96
Java OOP-class
Example: Adaptor
Using an Inner Class to Implement an Adapter
import java.util.Enumeration;
import java.util.NoSuchElementException;
public class Stack {
private java.util.Vector items;
// ... code for Stack's methods and constructors not shown...
public Enumeration enumerator() {
return new StackEnum();
}
class StackEnum implements Enumeration {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
}
}
97
Java OOP-class
Anonymous Class
You can declare an inner class without naming it.
Example: (Rewrite the previous slide.)
public class Stack {
private Vector items;
...//code for Stack's methods and constructors not shown...
public Enumeration enumerator() {
return new Enumeration() {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
};
}
}
98
Java OOP-class
Upcasting and Polymorphism(1/4)
Upcasting: Taking an object reference and treating it as a
reference to its base type is called upcasting, because of the
way inheritance trees are drawn with the base class at the top.
.
99
Java OOP-class
Upcasting and Polymorphism (2/4)
Polymorphism: In Java, the principle that the actual type of the
object determines the method to be called is called polymorphism.
class Shape {
void draw( ) {}
void erase( ) {}
}
class Circle extends Shape {
void draw( ) {
System.out.println("Circle.draw( ) ");
}
void erase( ) {System.out.println("Circle.erase( )");}
}
Shape
draw()
erase()
Square
draw()
erase()
Triangle
draw()
erase()
Circle
draw()
erase()
100
Java OOP-class
class Square extends Shape {
void draw( ) {
System.out.println("Square.draw( ) ");
}
void erase( ) {System.out.println("Square.erase( )");}}
class Triangle extends Shape {
void draw( ) {
System.out.println("Triangle.draw( )");
}
void erase( ) {System.out.println("Triangle.erase( )");}
}
Upcasting and Polymorphism (3/4)
101
Java OOP-class
public class Shapes {
public static Shape randShape() {
switch((int) (Math.random()*3)) {
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
default : return new Circle();}
}
public static void main(String[] args) {
Shape[] s = new Shape[9];
for (int i = 0; i < s.length; i++)
s[i] = randShape();
//Make polymorphism method calls:
for (int i = 0; i < s.length; i++) s[i].draw();
}
}
Upcasting and Polymorphism (4/4)
102
Java OOP-class
Polymorphism in C++ (1/2)
// polymo.cpp -- CopyWrong by [email protected]
#include <iostream.h>
class Shape{
public:
virtual // run
void draw( ) { cout << "drawing\n"; }
};
class Line: public Shape{
public:
void draw( ) { cout << "draw a line\n"; }
};
class Circle: public Shape{
public:
void draw( ) { cout << "here is a circle\n"; }
};
103
Java OOP-class
Polymorphism in C++ (2/2)
int main(){
Circle * ppp;
Shape * fig[9];
// ppp = new Shape(); // error
ppp = (Circle *)new Shape();
ppp -> draw();
ppp = (Circle *)new Line(); ppp -> draw();
ppp = new Circle(); ppp -> draw();
cout << "======" << endl;
fig[0] = new Line();
fig[1] = new Circle();
fig[2] = new Circle();
fig[3] = new Line(); fig[4] = new Circle();
for(int k=0; k<5; k++){
fig[k] -> draw();
}
}
104
Java OOP-class
Java: OOP, Object, Class
http://www.csie.nctu.edu.tw/~tsaiwn/course/java/