Software Design and Construction 1 SOFT2201 / COMP9201
OO Theory in Java
Dr. Grane School of Computer Science
The University of 1
Copyright warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING
This material has been reproduced and communicated to you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under
the Act.
Do not remove this notice.
The University of 2
Overview
– Types
– Encapsulation
– Inheritance
– Variable Binding & Polymorphism
– VirtualDispatch
– Abstract Classes
– Interfaces
The University of 3
Types in Java
– Overview
– Java is a strongly typed language
– Primitivetypes:built-intypesofthevirtualmachines
• Cannot be changed by programs
• Have same meaning across computer platforms
– Compositionaltypes • Interfaces
• Classes The University of 4
Primitive Types in Java
– Primitive types represent basic data-types
– In-built and cannot be changed in programs
– Integral types
– byte, short, int, long
– Floating point number types – float, double
– Character type – char
– Boolean
– boolean
The University of 5
Integral and Floating Types
Type
Internal
Smallest Value
Largest Value
byte
8 bits
-128
+127
short
16 bits
-32,768
+32,767
int
32 bits
-2,147,483,648
+2,147,483,647
long
64 bits
-2.3E+18
+2.3E+18
float
32 bits
-/+1.4e-45
-/+3.4e+38
double
64 bits
-/+4.9e-324
-/+1.7e+308d
The University of 6
Conversion between Primitive Types
– Implicit widening of integral & floating point number types – bytetoshort,int,long,float,ordouble
– shorttoint,long,float,ordouble
– chartoint,long,float,ordouble
– inttolong,float,ordouble – longtofloatordouble
– floattodouble
– Everything else requires type casts or is not possible The University of 7
Casting/Widening Matrix
From/To
byte
char
short
int
long
float
double
boole an
byte
n/a
char
(byte)
(short)
n/a
short
(byte)
(char)
n/a
int
(byte)
(char)
(short)
n/a
long
(byte)
(char)
(short)
(int)
n/a
float
(byte)
(char)
(short)
(int)
(long)
n/a
double
(byte)
(char)
(short)
(int)
(long)
(float)
n/a
boolean
n/a
n/a
n/a
n/a
n/a
n/a
n/a
The University of 8
Example for Implicit Widening and Casting
…
byte x = 10;
/* implicit widening */
short y = x; long z = x; float f = x;
/* casting */
byte p = (byte) z; short q = (short) f;
The University of 9
Silent Failure of Types
– Example:
…
int i = Integer.MAX_VALUE; System.out.println(i);
i = i + 1; System.out.println(i);
…
– Integeroverflowoccursforvariablei
– Type system cannot prevent this at compile-time
– weaknotionofcorrectness The University of 10
Operators and Primitive Types
– Special rules for results of operators
– Type inference deduces type of expressions – Example:
…
byte a = 1;
byte b = 2;
byte c = a + b; /* that gives an error */ byted=a–b; /*thatgivesanerror*/ …
The University of 11
Operators and Primitive Types
Java Language Specification
5.6.2. Binary Numeric Promotion
…
2.Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
•If either operand is of type double, the other is converted to double. •Otherwise, if either operand is of type float, the other is converted to float. •Otherwise, if either operand is of type long, the other is converted to long. •Otherwise, both operands are converted to type int.
The University of 12
Primitive Types
– Basic data-types
– BehavethesameonallplatformsrunningJava’svirtualmachine
– Primitive Types are not classes nor interfaces
– Primitive Types are building blocks for more complex types
– Beside storing of the actual value there is very little additional overhead
– Notethatclasseshaveextrainformationtokeepofdynamicruntime info
– Operations on primitive data-types are very efficient
The University of 13
Classes in Java
– Classes are types
– Compositetypeconsistingoffields(=state)andmethods(=behavior)
– ClassAbstraction
– Separate class implementation from the use of a class
– Userofaclassdoesnotneedtoknowtheimplementation/justthe public methods
– Theimplementorprovidestheimplementationoftheclass
– Thedetailsareencapsulatedandhiddenfromtheuser
– Class creates objects (instantiate)
– Object communicates with each other via methods
The University of 14
Classes
– A basic class has a name, fields, and methods: Name of Class
Fields Methods
Rectangle
width height
area ( )
The University of 15
Classes (cont’d)
– The basic syntax for a class is
class
}
– Example:
The University of 16
class Rectangle {
}
Adding Fields: Class Rectangle with Fields
– Addfields
public class Rectangle {
public double width, height;
}
– The fields (data) are also called the instance variables
– Fields can be
– Primitivetypes(int,bool,etc.)
– Referencestootherclassinstances
The University of 17
Adding Methods
– To change / retrieve state of a class, methods are necessary
– Methods are declared inside the body
– Methodsaremessagesinanobject-orientedprogrammingsense
– A return type must be specified
– A list of arguments with their types must be specified
– The general form of a method declaration is:
type Method (argument-list) { Method-body;
}
The University of 18
Adding Methods to Rectangle
public class Rectangle { public double width, height;
public void setWidth(double w) { width = w;
}
public void setHeight(double h) {
height = h; }
public double area() { return width * height;
}
}
Fields
Method Body
The University of 19
Mutators
– Methods that change the state of a class object are called mutators – Example:
public void setWidth(double w) { width = w;
}
public void setHeight(double h) {
height = h; }
– Givesclientsoftheclasswriteaccesstothestate
The University of 20
Accessor
– Methods that read the state of a class object are called accessors
– Example:
public double area() { return width * height;
}
– Gives clients of the class read access to the state The University of 21
Constructors
– Special method in class whose task is to initialise fields of the class
– The name is the same name as class
– Constructors are invoked whenever an object of that class is created
– It is called ‘constructor’ because it constructs values of data members.
– A constructor cannot return a value
– There can be several constructors for a class
– Default constructor with no parameters
– Parameterised constructors
The University of 22
Example: Default Constructor
– Default constructor
public class Rectangle { public double width, height; // default constructor public Rectangle() {
width = 1.0;
height = 1.0; }
}
– Java has a synthesised default constructor when not specified
The University of 23
Example: Parameterised Constructor
– Parameterised constructor:
public class Rectangle { public double width, height;
// parameterised constructor
public Rectangle(double w, double h) {
width = w;
height = h; }
}
The University of 24
Example: Multiple Constructors
– Default and parameterised constructor (overloading)
public class Rectangle { public double width, height; // default constructor public Rectangle() {
width = 1.0;
height = 1.0; }
// parameterised constructor
public Rectangle(double w, double h) {
width = w;
height = h; }
}
The University of 25
Creating Instances of a Class
– Objects are created dynamically using the new keyword.
– The new operator creates a new object on the heap
– Theobjectwillbeselectedasacandidateifnotfurtherused
– Theobjectbecomesacandidateforautomaticgarbagecollection
– Garbagecollectionkicksinperiodicallyandreleasescandidates
– developers don’t need to delete their own objects
– Example:
– Define a reference variable X of type class that points to a new
instance The University of 26
Example: Creating Instances of a Class
– rec1 and rec2 refer to Rectangle objects
rec1 = new Rectangle();
rec2 = new Rectangle(10,1);
– First instance calls default constructor
– Second instance calls parameterised constructor
The University of 27
Copy Constructor
– Java has no copy constructor
– We can simulate copy constructor by having a constructor with
objects of same type as argument
– All classes are derived from class Object
– Object has the method clone()
The University of 28
Example: Copy Constructor
– Copy constructor
public class Rectangle {
public double width, height; // copy constructor
public Rectangle(Rectangle o) {
width = o.width;
height = o.height; }
}
The University of 29
Accessing Fields and Methods
– Access is done via the . operator
– Access to field and methods of an instance in the same style
Example: Accessing fields / methods
– Using object methods:
Rectangle rec = new Rectangle();
rec.width = 1.0; rec.height = 100.0; double area = rec.area();
send ‘message’ area to an instance of type Rectangle which rec is referring to
The University of 31
Access Modifiers
– Access modifiers provide encapsulation for object-oriented programming
– Protect state from client
– Access modifiers work on different levels: – Classlevel
– Memberlevel – Clientlevel
The University of 32
Access Modifier: public
– A class that is labeled as public is accessible to all other classes inside and outside a package
package com.foo.hoo;
import com.foo.goo;
public class test2 { public void test(){
test1 x = new test1(); }
}
package com.foo.goo;
public class test1 { public void test();
}
The University of 33
Access Modifier: public
– A class marked as public is accessible to all classes with the import statement
– There is no need for import statement if a public class is used in the same package
The University of 34
Access Modifier: default
– Default access is a class definition with no specified access qualifier
– Classes marked with default access are visible only in package but not outside of package
– Note that protected and private classes are not available for packages
The University of 35
Member access modifiers for methods and fields
– Public
– Accessiblebyclient,package,class,andsub-classes
– Protected
– Accessiblebypackage,class,andsub-classes
– ‘Default’
– Accessiblebyclassandpackage
– Private
– Accessiblebyclassitselfonly
The University of 36
Example: Member access modifiers
– Example: public
public class Rectangle { public double width, height;
}
// client can access state Rectangle x = new Rectangle(); x.width = 100;
x.height = 100;
The University of 37
Example: Member access modifiers
– Example: protected
public class Rectangle { protected double width, height;
}
// client cannot access state Rectangle x = new Rectangle(); x.width = 100; // access error! x.height = 100; // access error!
The University of 38
Example: Member access modifiers
– Example: private
public class Rectangle {
private double width, height; Rectangle(double w, double h) {
width = w; // access is ok
height = h; // access is ok }
}
public class Square extends Rectangle {
Square(double w) { super.Rectangle(w,w);
}
void setWidth(double w) {
super.width = w; // access error!
super.height = w; // access error!
}
The University of Sydney }
Page 39
Encapsulation
– Wrap data/state and methods into a class as a single unit
– Multiple instances can be generated
– Protect state via setter (mutator)/getter (accessor) methods
The University of 40
Sub-Classes
– Classes permit inheritance
– Methods and fields from a super-class can be inherited
– Idealforsoftware-engineering – Reuseofcode
– Java uses “extends” keyword for extending from existing class
– Single-inheritanceparadigm
– Class hierarchy has a tree structure
– If no super-class is specified, default class Object becomes
super-class
The University of 41
Inheritance
– Sub-class inherits from super-class: methods, variables, … – Reusestructureandbehaviorfromsuper-class
– Single inheritance for classes
The University of 42
Variable Binding, Polymorphism
– Object (on heap) has single type when created – Typecannotchangethroughoutitslifetime
– Reference variables point to null or an object
– Type of object and type of reference variable may differ
– e.g.,Shapex=newRectangle(4,2);
– Understand the difference
– Runtimetypevscompile-timetype
– Polymorphism:
– Referencevariablemayreferencedifferentlytypedobject – Mustbeasub-typeof
The University of 43
Virtual Dispatch
– Methods in Java permit a late binding
– Reference variable and its type does not tell which method is
really invoked
– The type of reference variable and class instance may differ
– Class variables may override methods of super classes
– The method invoked is determined by the type of the class instance
– Binding is of great importance to understand OO The University of 44
Example: Virtual Dispatch
– Example:
public class Shape /* extends Object */ {
double area() { }
}
public class Rectangle extends Shape {
double area() { }
}
…
Shape x = new Shape(); Shape y = new Rectangle();
double a1 = x.area() // invokes area of Shape double a2 = y.area() // invokes area of Rectangle
The University of 45
Abstract Classes
– Method implementations may be deferred to sub-classes
– Requires own key-word abstract for class/method
– No instance of an abstract class can be generated
The University of 46
Interfaces
– Java has no multi-inheritance
– Interface are a way out (introduction of multi-inheritance via the back-door)
– Interfaces are a class contract that ensures that a class implements a set of methods.
– Interfaces can inherit from other interfaces
– Ensures that a class has a certain set of behavior
– Interfaces are specified so that they form a directed acyclic graph
– Methods declared in an interface are always public and abstract
– Variables are permitted if they are static and final only
The University of 47
Example: Interface
// definition of interface public interface A {
int foo(int x);
}
// class X implements interface A class X implements A {
int foo(int x) {
return x;
} }
The University of 48
Example: Interface
– Inheritanceininterfaces
// definition of interface public interface A {
int foo(int x);
}
public interface B extends A{ int hoo(int x);
}
– InterfaceBhasmethodsfoo()andhoo()
The University of 49