34
4: Initialization & Cleanup Guaranteed initialization with the constructor Method overloading Distinguishing overloaded methods Overloading with primitives Overloading on return values Default constructors The this keyword Calling constructors from constructors The meaning of static Cleanup: finalization and garbage collection Member initialization Specifying initialization Constructor initialization Order of initialization Static data initialization Explicit static initialization Non-static instance initialization Array initialization Multidimensional arrays

4: Initialization & Cleanup

Embed Size (px)

DESCRIPTION

4: Initialization & Cleanup. Guaranteed initialization with the constructor Method overloading Distinguishing overloaded methods Overloading with primitives Overloading on return values Default constructors The this keyword Calling constructors from constructors The meaning of static - PowerPoint PPT Presentation

Citation preview

4: Initialization & Cleanup• Guaranteed initialization with the constructor• Method overloading• Distinguishing overloaded methods

– Overloading with primitives– Overloading on return values

• Default constructors• The this keyword

– Calling constructors from constructors– The meaning of static

• Cleanup: finalization and garbage collection• Member initialization

– Specifying initialization– Constructor initialization– Order of initialization– Static data initialization– Explicit static initialization– Non-static instance initialization

• Array initialization– Multidimensional arrays

What Is an Object?• Objects are key to understanding object-oriented technology.

– Examples : your desk, your television set, your bicycle. • These real-world objects share two characteristics: state and behavior.

– For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail).

– Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).

• Software objects are modeled after real-world objects– they too have state and behavior. – A software object maintains its state in one or more variables. A variable

is an item of data named by an identifier. – A software object implements its behavior with methods. A method is a

function (subroutine) associated with an object. • --------------------------------------------------------------------------------• Definition: An object is a software bundle of variables and related

methods. • --------------------------------------------------------------------------------

What Is a Class?• In the real world, you often have many objects of the same kind.

– For example, your bicycle is just one of many bicycles in the world. – Using object-oriented terminology, we say that your bicycle object is an

instance of the class of objects known as bicycles. – Bicycles have some state (current gear, current cadence, two wheels) and

behavior (change gears, brake) in common. – However, each bicycle's state is independent of and can be different from

that of other bicycles. • In object-oriented software, it's also possible to have many objects of

the same kind that share characteristics: – You can take advantage of the fact that objects of the same kind are

similar and you can create a blueprint for those objects. A software blueprint for objects is called a class.

• --------------------------------------------------------------------------------• Definition: A class is a blueprint, or prototype, that defines the

variables and the methods common to all objects of a certain kind. • --------------------------------------------------------------------------------

Class Example

What Is a Message? • A single object alone is generally not very useful. Instead, an object

usually appears as a component of a larger program or application that contains many other objects.

• Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B

• The next figure shows the three components that comprise a message: – The object to which the message is addressed (YourBicycle) – The name of the method to perform (changeGears) – Any parameters needed by the method (lowerGear)

YourBicycle.changeGears(lowerGear)

Class Examplepublic class Rectangle { public int width = 0; public int height = 0; public Point origin;

public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; }

//A method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; }

//A method for computing the area of the rectangle public int area() { return width * height; }}

public class Point { public int x = 0; public int y = 0;

//A constructor! public Point(int x0, int y0) { x = x0; y = y0; }}

Class ExamplePoint origin_one = new Point(23, 94);

Rectangle rect_one = new Rectangle(origin_one, 100, 200);

Why need we a constructor?public class Rectangle { public int width = 0; public int height = 0; public Point origin;

//A method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; }

//A method for computing the area of //the rectangle

public int area() { return width * height; }}

public class Application{ public SomeMethod() { Rectangle re=new Rectangle();

//Invalid Access!!! re.move(20,10); System.out.print(re.origin.x); System.out.print(re.origin.y); }}

Guaranteed initialization with the constructor• In Java, the class designer can guarantee initialization of every object by

providing a special method called a constructor. • If a class has a constructor, Java automatically calls that constructor wh

en an object is created. • The name of the constructor must match the name of the class exactly.

It has no return value

public class Point { public int x = 0; public int y = 0; //A constructor! public Point(int x, int y) { this.x = x; this.y = y; }}Now, when an object is created: new Point(1,2);storage is allocated and the constructor is called. It is guaranteed that the object wi

ll be properly initialized before you can get your hands on it

Initialization with the constructorpublic class Rectangle { public int width = 0; public int height = 0; public Point origin;

//Constructor public Rectangle() { origin = new Point(0,0); width = 1; height = 1; }

//A method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; }

//A method for computing the area of the rectangle

public int area() { return width * height; }}

public class Application{ public SomeMethod() { Rectangle re=new Rectangle();

//OK now!!! re.move(20,10);

System.out.print(re.origin.x); System.out.print(re.origin.y); }}

If we want to create objects in different wayspublic class Rectangle { public int width = 0; public int height = 0; public Point origin;

//Constructor public Rectangle() { origin = new Point(0,0); width = 1; height = 1; }

public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; }

//A method for computing the area of the rectangle

public int area() { return width * height; }

//A method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; }//Another method for moving the rectanglepublic void move(float xy) { origin.x = (int)xy; origin.y = (int)xy; }}//End of class Rectangle

public class Application{ public SomeMethod() { Rectangle re1=new Rectangle(); Rectangle re2=new Rectangle(

new Point(30,30), 10, 20); //Do some processing re1.move(20,10); re1.move(30.5); re2.move(20,10); re2.move(40.5); }}

Method overloadingMethod overloading: several methods share the same

method name with different argument types.

class Tree { int height; Tree() { prt("Planting a seedling");

height = 0; } Tree(int i) { prt("Creating new Tree that is " + i + " feet tall"); height = i; } void info() {

prt("Tree is " + height + " feet tall"); } void info(String s) {

prt(s + ": Tree is " + height + " feet tall"); } static void prt(String s) {

System.out.println(s); } }

Method overloadingEven differences in the ordering of arguments are suffici

ent to distinguish two methods

public class OverloadingOrder { static void print(String s, int i) {

System.out.println( "String: " + s + ", int: " + i); } static void print(int i, String s) {

System.out.println( "int: " + i + ", String: " + s); } public static void main(String[] args) {

print("String first", 11); print(99, "Int first"); }

} ///:~

Method overloading• Overloading with primitives

– A primitive can be automatically promoted from a smaller type to a larger one, and this can be slightly confusing in combination with overloading.

– For example, a constant value 5 is treated as an int, so if an overloaded method is available that takes an int, it is used.

• void func(int a) {…}• f(5);

– if you have a data type (e.g. int) that is smaller than the argument (long) in the method, that data type int is promoted to long.

• void func(long a) {…}• f(5);

• you cannot use return value types to distinguish overloaded methods. void f() {} int f() {}

Default constructors– If you create a class that has no constructors, the

compiler will automatically create a default constructor for you.

class Bird { int i; } public class DefaultConstructor {

public static void main(String[] args) { Bird nc = new Bird(); // default!

} } ///:~ new Bird(); //OK!!!

– However, if you define any constructors (with or without arguments), the compiler will not synthesize one for you:

class Bush { Bush(int i) {} Bush(double d) {}

}

new Bush(); //Error!!!

Exercise6.Create a class called Dog with an overloaded bark( ) method. This

method should be overloaded based on various primitive data types, and print different types of barking, howling, etc., depending on which overloaded version is called. Write a main( ) that calls all the different versions.

The this keywordclass Banana {

int num;void f(int i) { num=i; // this.num=i; }

} Banana a = new Banana(), b = new Banana(); a.f(1); b.f(2); You may wonder that how f() could know which object is being processed?

Banana.f(a,1); Banana.f(b,2); – This is internal and you can’t write these expressions and get the co

mpiler to accept them, but it gives you an idea of what’s happening• Suppose you’re inside a method and you’d like to get the reference to t

he current objectclass Apricot {

void pick() { /* ... */ } void pit() { pick(); /* this.pick( ); */ }

} Inside pit( ), you could say this.pick( ) but there’s no need to.

“ this “ keywordpublic class Rectangle { public int width = 0; public int height = 0; public Point origin;………….//computing the area of the rectangle public int area() { return width * height; // return this.width*this.height //maybe need not use but available in class methods }//A method for moving the rectangle public void move(int x, int y) { origin.x = x; //this.origin.x origin.y = y; }}//End of class Rectangle}

Internal realization ( C simulation)……//computing the area of the rectangleint area(Rectangle *this) { return this->width*this->height }//A method for moving the rectanglevoid move(Rectangle *this, int x, int y) { this->origin.x = x; this->origin.y = y; }

//Do some processingmove(re1, 20,10); area(re1);move(re2, 20,10); area(re2);}}

public class Point { public int x = 0; public int y = 0;

//A constructor! public Point(int x, int y) { this.x = x; this.y = y; }}

this: the reference to the object the method has been called

for

The this keyword

The this keywordThe this keyword is used only for those special cases in which you n

eed to explicitly use the reference to the current object. public class Leaf {

int i = 0; Leaf increment() {

i++; return this;

} void print() { System.out.println("i = " + i); } public static void main(String[] args) {

Leaf x = new Leaf(); x.increment().increment().increment().print(); }

} ///:~

Calling constructors from constructorspublic class Flower {

int petalCount = 0; String s = new String("null");

Flower(int petals) { petalCount = petals; System.out.println( "Constructor w/ int arg only, petalCount=

" + petalCount); } Flower(String ss) {

System.out.println( "Constructor w/ String arg only, s=" + ss); s = ss; } Flower(String s, int petals) {

this(petals); //! this(s); // Can't call two! this.s = s; // Another use of "this" System.out.println("String & int args");

} Flower() {

this("hi", 47); System.out.println("default constructor (no args)");

} void print() { //! this(11); // Not inside non-constructor! System.out.println( "petalCount = " + petalCount + " s = "+ s); }

The meaning of static method• It means that there is no this for that particular metho

d.• You cannot call non-static methods /or access non-stati

c field from inside static methods .(but reverse OK)

• You can call a static method for the class itself, without any object.

public class Demotion { static void prt(String s) { System.out.println(s); }

}public class AAA{

void f1(char x) { Demotion .prt("f1(char)");

} }

The meaning of static field

There’s only a single piece of storage for a static field, regardless of how many objects are created.

(It’s kind of global data/variable for all objects of the same class)

You can access a static field for the class itself, without any object.

class IntX { static int x; public int getx() { return x; } public void setX(int newX) { x = newX; }}. . .IntX myX = new IntX();IntX myX2 = new IntX();myX.setX(1);myX2.x = 2;System.out.println("myX.x = " + myX.getx());System.out.println("myX2.x = " + myX2.getx());. . .

myX.x = 2myX2.x = 2

class IntX { int x; public int getx() { return x; } public void setX(int newX) { x = newX; }}. . .IntX myX = new IntX();IntX myX2 = new IntX();myX.setX(1);myX2.x = 2;System.out.println("myX.x = " + myX.getx());System.out.println("myX2.x = " + myX2.getx

());. . .

myX.x = 1myX2.x = 2

class IntX { static int x; static public int getx() { return x; } static public void setX(int newX) { x = newX; }}. . .IntX myX = new IntX();IntX myX2 = new IntX();myX.setX(1);myX2.x = 2;System.out.println("myX.x = " + myX.getx());System.out.println("myX2.x = " + myX2.getx());. . .

myX.x = 2myX2.x = 2

class IntX { int x; static public int getx() { return x; } static public void setX(int newX) { x = newX; }}. . .IntX myX = new IntX();IntX myX2 = new IntX();myX.setX(1);myX2.x = 2;System.out.println("myX.x = " + myX.getx());System.out.println("myX2.x = " + myX2.getx

());. . .

When you try to compile this version of IntX, the compiler displays an error .

Member initialization: • Specifying initialization

– Simply assign the initial value at the point you define the variable– Order of initialization

• Within a class, the order of specifying initialization is determined by the order that the variables are defined within the class

class Measurement { boolean b = true; char c = 'x';; short s = 0xff; Depth d= new Depth(); //nonprimitive member !!!

}• Constructor initialization

class Counter { int i; Counter() {

i = 7; } // . . .

Order of initialization• The order of initialization is statics first, then (in the

case of new object): Memory allocation=>zero clear=>specifying init

=>Constructor initialization

• Within a class, the order of specifying initialization is determined by the order that the variables are defined within the class.

• The static initialization occurs only ONCE. T hey are initialized only when the first object is created (or the first static access occurs).

• In fact, the static initialization takes place when JVM loads a class file into its memory.

class Bowl { Bowl(int marker) {

System.out.println("Bowl(" + marker + ")"); } void f(int marker) {

System.out.println("f(" + marker + ")"); }

}

1. class Table { 2. static Bowl b1 = new Bowl(1); 3. Table() { System.out.println("Table()"); b2.f(1); } 4. void f2(int marker) { System.out.println("f2(" + marker +

")"); } 5. static Bowl b2 = new Bowl(2);6. } 7. class Cupboard { 8. Bowl b3 = new Bowl(3); 9. static Bowl b4 = new Bowl(4); 10. Cupboard() { System.out.println("Cupboard()"); b4.f(2); }11. void f3(int marker) { System.out.println("f3(" + marker +

")"); } 12. static Bowl b5 = new Bowl(5); 13. }14. public class StaticInitialization { 15. public static void main(String[] args) { 16. System.out.println( "Creating new Cupboard() in mai

n"); 17. new Cupboard(); 18. System.out.println( "Creating new Cupboard() in mai

n"); 19. new Cupboard(); 20. t2.f2(1); t3.f3(1); 21. } 22. static Table t2 = new Table(); 23. static Cupboard t3 = new Cupboard(); 24. } ///:~

java StaticInitialization

1. Bowl(1)2. Bowl(2)3. Table() 4. f(1) 5. Bowl(4) 6. Bowl(5) 7. Bowl(3) 8. Cupboard() 9. f(2) 10. Creating new

Cupboard() in main

11. Bowl(3) 12. Cupboard() 13. f(2) 14. Creating new

Cupboard() in main

15. Bowl(3) 16. Cupboard()17. f(2)18. f2(1)19. f3(1)

• Explicit static initializationclass Spoon { static int i; static { i = 47; } }

• Non-static instance initializationpublic class Mugs { static Test monitor = new Test(); Mug c1; Mug c2; { c1 = new Mug(1); c2 = new Mug(2); System.out.println("c1 & c2 initialized"); }…

Array initializationpublic class Arrays {

public static void main(String[] args) { int[] a1 = { 1, 2, 3, 4, 5 }; int[] a2; a2 = a1; for(int i = 0; i < a2.length; i++) a2[i]++; for(int i = 0; i < a1.length; i++)

System.out.println( "a1[" + i + "] = " + a1[i]); }

} ///:~

a1[0] = 2

a1[1] = 3

a1[2] = 4

a1[3] = 5

a1[4] = 6

Array of Objectsimport java.util.*; public class ArrayClassObj {

static Random rand = new Random(); static int pRand(int mod) {

return Math.abs(rand.nextInt()) % mod + 1; } public static void main(String[] args) {

Integer[] a = new Integer[ pRand(20) ]; System.out.println( "length of a = " + a.length);

for(int i = 0; i < a.length; i++) { a[i] = new Integer( pRand(500) ); System.out.println( "a[" + i + "] = " + a[i]);

} }

} ///:~

Multidimensional arraysint[][] a1 = { { 1, 2, 3, }, { 4, 5, 6, }, };

int[][][] a2 = new int[2][2][4];

Integer[][] a4 = { { new Integer(1), new Integer(2)}, { new Integer(3), new Integer(4)}, { new Integer(5), new Integer(6)}, };

==========================int[] a1; You can also put the square brackets after the identifier to produce

exactly the same meaning: int a1[];

Exercise Exercise 14: (1) Create a class with a static String field that is initialized a

t the point of definition, and another one that is initialized by the static block. Add a static method that prints both fields and demonstrates that they are both initialized before they are used.(version 4 P.132)