340 likes | 434 Views
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
E N D
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. • --------------------------------------------------------------------------------
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 Example public class Point { public int x = 0; public int y = 0; //A constructor! public Point(int x0, int y0) { x = x0; y = y0; } } public 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; } }
Class Example Point origin_one = new Point(23, 94); Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Why need we a constructor? 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); } } 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; } }
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 when 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 will be properly initialized before you can get your hands on it
Initialization with the constructor 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); } } public 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; } }
If we want to create objects in different ways //A method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; } //Another method for moving the rectangle public 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); } } public 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; }
Method overloading Method 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"); } staticvoid prt(String s) { System.out.println(s); } }
Method overloading Even differences in the ordering of arguments are sufficient to distinguish two methods publicclass OverloadingOrder { staticvoid print(String s, int i) { System.out.println( "String: " + s + ", int: " + i); } staticvoid print(int i, String s) { System.out.println( "int: " + i + ", String: " + s); } publicstaticvoid 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 typeint 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; } publicclass DefaultConstructor { publicstaticvoid 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!!!
Exercise 6.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 keyword class 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 compiler 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 the current object class Apricot { void pick() { /* ... */ } void pit() { pick(); /* this.pick(); */ } } Inside pit(), you could say this.pick() but there’s no need to.
“ this “ keyword public 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 rectangle int area(Rectangle *this) { return this->width*this->height } //A method for moving the rectangle void move(Rectangle *this, int x, int y) { this->origin.x = x; this->origin.y = y; } //Do some processing move(re1, 20,10); area(re1); move(re2, 20,10); area(re2); } }
The this keyword this: the reference to the object the method has been called for 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; } }
The this keyword The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object. publicclass Leaf { int i = 0; Leaf increment() { i++; returnthis; } void print() { System.out.println("i = " + i); } publicstaticvoid main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment().print(); } } ///:~
Calling constructors from constructors publicclass 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 method. • You cannot call non-static methods /or access non-static fieldfrom inside static methods . (but reverse OK) • You can call a static method for the class itself, without any object. publicclass Demotion { staticvoid 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 staticfield for the class itself, without any object.
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 = 1 myX2.x = 2 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 = 2 myX2.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 . 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 = 2 myX2.x = 2
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. They are initialized only when the firstobject is created (or the firststatic 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 + ")"); } }
Bowl(1) • Bowl(2) • Table() • f(1) • Bowl(4) • Bowl(5) • Bowl(3) • Cupboard() • f(2) • Creating new Cupboard() in main • Bowl(3) • Cupboard() • f(2) • Creating new Cupboard() in main • Bowl(3) • Cupboard() • f(2) • f2(1) • f3(1) • class Table { • static Bowl b1 = new Bowl(1); • Table() { System.out.println("Table()"); b2.f(1); } • void f2(int marker) { System.out.println("f2(" + marker + ")"); } • static Bowl b2 = new Bowl(2); • } • class Cupboard { • Bowl b3 = new Bowl(3); • static Bowl b4 = new Bowl(4); • Cupboard() { System.out.println("Cupboard()"); b4.f(2); } • void f3(int marker) { System.out.println("f3(" + marker + ")"); } • static Bowl b5 = new Bowl(5); • } • publicclass StaticInitialization { • publicstaticvoid main(String[] args) { • System.out.println( "Creating new Cupboard() in main"); • new Cupboard(); • System.out.println( "Creating new Cupboard() in main"); • new Cupboard(); • t2.f2(1); t3.f3(1); • } • static Table t2 = new Table(); • static Cupboard t3 = new Cupboard(); • } ///:~ java StaticInitialization
Explicit static initialization class Spoon { static int i; static { i = 47; } } • Non-static instance initialization public 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 initialization publicclass Arrays { publicstaticvoid 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 Objects import java.util.*; publicclass ArrayClassObj { static Random rand = new Random(); staticint pRand(int mod) { return Math.abs(rand.nextInt()) % mod + 1; } publicstaticvoid main(String[] args) { Integer[] a = newInteger[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 arrays int[][] a1 = { { 1, 2, 3, }, { 4, 5, 6, }, }; int[][][] a2 = newint[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 at 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)