Objects Classes and • • • •
Re Refe fere renc nce e ttyp ypes es and and tthe heir ir characteristics Clas lass D Def efin init itio ion n Const Construc ructor tors s an and d Ob Objec jectt Cr Creat eation ion Spe Specia ciall ob objec jects ts:: St Strin rings gs and and A Arra rrays ys
OOAD 1998/99 Claudia Niederée, Joachim W. Schmidt Software Systems Institute
[email protected] http://www.sts.tu-harburg.de
Reference Types • Predef Predefine ined d or user-d user-defi efine ned d Classe Classes s • String • Array • The values values of reference reference types types are not manip manipulat ulated ed directly. • Instead Instead handle handles s (referenc (references) es) to the actual actual value values s are used.
OOAD98/99-ST S-Objects and Classes
2
1
Reference Type Variables • A vari variab able le of a refe refere renc nce e type contains a reference to an anonymous object in storage.
a object
• An uninit uninitial ialize ized d var variab iable le contains a null-reference.
a b
Point a,b;
• Obje Object cts s are are cr crea eate ted d at at run-time. new Point(0,0);
0 0
• Obje Object cts s are are anon anonym ymou ous. s. • They They have have an an immut immutabl able e iden identity tity.. OOAD98/99-ST S-Objects and Classes
3
Binding Reference Type Variables • Assi Assign gnin ing g an an obj objec ectt to a variable, the variable gets a reference to the object as its value. a = new Point(0,0); b = new Point(3,4);
• Assi Assign gnin ing g valu values es of of other other variables means assigning the references! The value of the object does not change a = b; • May May be be a pitfa pitfall ll,, a as s the the object may change OOAD98/99-ST S-Objects and Classes
0 0
a b
3 4
a b
0 0 3 4 4
2
Comparing Objects • Comparing Comparing two refer reference ence type variables variables means means comparing the references they contain and, thus, comparing the identity of the referenced objects. a b c
d
3 4
a == b
3 4
a != c
d == null
OOAD98/99-ST S-Objects and Classes
5
Comparing the Contents of Objects • The conte contents nts of of objects objects belongin belonging g to pre-de pre-defined fined classes can be compared using the method equals. • If you you defin define e a class class of y your our own, own, equals by default only compares references, as == does. => You have to override equals for newly defined classes.
OOAD98/99-ST S-Objects and Classes
6
3
Creating New Data Types: class • Class keyword keyword introdu introduces ces definiti definition on of new data ttype ype class ATypeName { /* class body goes here */ } ATypeName a = new ATypeName();
• Data mem members bers class DataOnly { int i; float f; boolean b; }
• Each Each inst instan ance ce of DataOnly DataOnly gets gets its own copy of the data members • In a class, class, primitiv primitives es get get defau default lt values values.. OOAD98/99-ST S-Objects and Classes
7
Methods, Arguments and Return Values • Methods: Methods: “how you get get things things done in an object“ object“ – May inspect and and change the state state of the object – Traditionally called called “functions” – Can only be defined inside classes classes returnType methodName(/* argument list */) { /* Method body */ }
• Exam Exampl ple e met metho hod d cal call: l: int x = a.f(); //
OOAD98/99-ST S-Objects and Classes
For object a
8
4
The Argument List • Types Types of the the objects objects to pass pass in to the the method method • Name Name (ide (identi ntifie fier) r) to use use for for each each one one • Whenever Whenever you seem to be passing passing object objects s in Java, Java, you‘re actually passing handles
void reset(Cell c) { reset(Cell c.setValue(0); }
Cell cell1 = new Cell();
cell1.setValue(4);
reset(cell1);
cell1.getValue();
OOAD98/99-ST S-Objects and Classes
9
this:: Handle to Current Object this public class Leaf { private int i = 0; Leaf increment() { i++; return this; } void print() { print() System.out.println(" System.out.println("i i = " + i); } public static void main(String args[]) { Leaf x = new Leaf();
x.increment().incre x.increment().increment().increment().p ment().increment().print(); rint(); } }
•
no this this in in static methods
OOAD98/99-ST S-Objects and Classes
10
5
Overloading on Return Values • Why not also also use use re retur turn n val values ues in in metho method d overloading? void f() {...} f() int f() {...}
• Then Then w wha hatt woul would d this this mea mean? n? f();
OOAD98/99-ST S-Objects and Classes
13
Default Constructor • Construct Constructors ors are needed needed to to create create instances instances (objects) of a class • Compiler Compiler provides provides one one for for you you if you you write write n no o constructor class Bird { int i; } public class DefaultConstructor { public static void main(String args[]) { Bird nc = new Bird(); // default! } } OOAD98/99-ST S-Objects and Classes
14
7
Constructor Definition class Rock { Rock() { // This is is the constructor System.out.println("Creating System.out.println(" Creating Rock"); } } public class SimpleConstructor { public static void main(String args[]) { main for(int i = 0; i < 10; i++) new Rock(); } }
OOAD98/99-ST S-Objects and Classes
15
Constructor Overloading • Like methods methods constr constructor uctors s may may be be overlo overloaded aded class Tree { int height; Tree() { System.out.println( System.out.println("A "A seedling"); height = 0; } Tree(int i) { System.out.println( System.out.println("A "A new Tree, " + i + " feet tall"); height = i; }
}
OOAD98/99-ST S-Objects and Classes
16
8
this in this in Constructors • A very very comm common on kin kind d to use use this is in constructors to initialize data members with the constructor's arguments public class Animal {
private int numberOfLegs; Animal(int numberOfLegs) {
this.numberOfLegs = numberOfLegs;
} }
OOAD98/99-ST S-Objects and Classes
17
Member Initialization void f() { f()
int i; // No initialization i++; }
• Produc Produces es compil compile-t e-time ime error error • Inside Inside cla class, ss, pri primitiv mitives es are are given given default default value values s if you you don’t specify values class Data { int i = 999; long l; // defaults to zero // ...
OOAD98/99-ST S-Objects and Classes
18
9
Constructor Initialization • Orde Orderr of init initia iali liza zati tion on – Order that data members members are defined in class • Static Static data data initi initiali alizat zation ion class Cupboard { Bowl b3 = new Bowl(3); static Bowl b4 = new Bowl(4); // ...
– b4 – b4 only only created on first access or when first object of class Cupboard is created Cupboard is
OOAD98/99-ST S-Objects and Classes
19
Arrays and Array Array Initialization • Arra Arrays ys are are obj objec ects ts int a1[]; int[] a1;
// this... // is the same as this!
Creates a handle, not the array. Can’t size it. • To crea create te an arr array ay of of primit primitive ives: s: int [] a1 = { 1, 2, 3, 4, 5 };
• Boun Bounds ds are are chec checke ked, d, length produces size of the array a1.length • If you do anythi anything ng wrong wrong either either the compil compiler er will will catc catch h it or an exception will be thrown
OOAD98/99-ST S-Objects and Classes
20
10
Arrays of Objects Objects • An arr array ay of of clas class s obje object cts: s: Animal[] a = new Animal[20]; System.out.println(a.length System.out.println(a.length + " animals"); for(int i = 0; i < a.length; i++) {
a[i] = new Animal((i % 2 + 1) * 2);
• Can also also use use brackete bracketed d list list (The size is is then fixed at compile-time) Integer[] a = { new Integer(1), new Integer(2), new Integer(3), };
OOAD98/99-ST S-Objects and Classes
21
Multi-dimensional Arrays • It is possib possible le to defin define e multi-di multi-dimens mensiona ionall arrays. arrays. int[][] a;
• The bracke brackets ts even even may may be distribute distributed d betwee between n typ type e and identifier. int[] a[];
• Initia Initializ lizati ation on can can be don done e direc directly tly int[][] a = { { 1, 2, 3 }, { 5, 6} };
• It can also be done done by nested nested iterations iterations over the array and its components.
OOAD98/99-ST S-Objects and Classes
22
11
Strings • Strings Strings are are immuta immutable ble objects objects of of the class String String.. • String String literal literals s are zero zero,, one or more more charac characters ters included within double quotes. • When a binding binding to a string string litera literall is execu executed ted for for the first time, a new String object is created. • If any any other other bindin bindings gs to this liter literal al appea appear, r, the respective variables will hold reference to the same object. String a = "abc"; String b = "abc";
a
•
• "abc"
b
OOAD98/99-ST S-Objects and Classes
23
String Constructors • String String objects objects can also also be be created created by calli calling ng a constructor. • String String construct constructors ors create create new new o object bjects s whenev whenever er they they are called. String c = new String("abc");
a "abc"
b c
"abc"
• There are severa severall construc constructors tors defin defined ed for for strings. strings. OOAD98/99-ST S-Objects and Classes
24
12
String Concatenation • String Strings s can be be concat concaten enate ated d by using using +. +. String c = "A " + "concatenation";
• The concate concatenatio nation n also also crea creates tes a new new String String object. object. • Values Values of other other types types can be be concaten concatenated ated to strings, strings, too. • They are implicitl implicitly y conve converted rted to String String.. String n = "Number " + 49;
OOAD98/99-ST S-Objects and Classes
25
Inside the Method Body • Variab Variable le declar declarati ation on and assig assignme nments nts • Operat Operation ions s on prim primiti itive ve data data typ types es • Obje Object ct crea creati tion on • Mess Messag age e se send ndin ing g • Iteration • Condit nditio iona nals ls
OOAD98/99-ST S-Objects and Classes
26