340 likes | 424 Vues
OO Support in Java: Classes (Part 2). INTRODUCTION. The following topics will be discussed: Constructor Methods Method Overloading. CONSTRUCTOR METHODS. Consider the following class definition: class Account { private String acctNo; private boolean active; private String owner;
E N D
INTRODUCTION • The following topics will be discussed: • Constructor Methods • Method Overloading
CONSTRUCTOR METHODS • Consider the following class definition: class Account { private String acctNo; private boolean active; private String owner; public void displayInfo( ) { System.out.println("Acct number: "+acctNo); System.out.println("Owner: "+owner); System.out.print("Status: "); if (!active) System.out.print("NOT "); System.out.println("ACTIVE"); } }
What happens when the following statements are executed? Account acct = new Account( ); acct.displayInfo( ); • When an object is created, its attributes should be initialized. Example: Account acct = new Account( ); acct.initialize("010-99333-03", "Nada Asyiqin", true); acct.displayInfo( ); Problem: It is easy to forget to initialize newly created objects.
Can object initialization be done during object creation? • Two common ways of initializing attributes during object creation: • Via instance variable initializers • Via constructor methods
Variable initializers Method 1: Instance Variable Initializer class Piggybank { private int cents = 0; private String owner = null; public void deposit(int amt) { cents += amt; } public void withdraw(int amt) { cents -= amt; } }
: Piggybank : Piggybank : Piggybank cents cents cents 0 0 0 owner owner owner null null null • For each Piggybankobject created, its instance variable centswill be initialized to 0 and owner to null. for (int i=0; i < 3; i++) new Piggybank( );
Method 2: Constructor Methods class Piggybank { private int cents; private String owner; public Piggybank( ) { cents = 0; owner = null; } public void deposit(int amt) { cents += amt; } public void withdraw(int amt) { cents -= amt; } } Constructor method
The constructor method is executed each time a Piggybank object is created. When executed, • the centsattribute of the created object is initialized to 0. • the ownerattribute is set to null.
: Piggybank : Piggybank : Piggybank cents cents cents 0 0 0 owner owner owner null null null • public Piggybank( ) { • cents = 0; • owner = null; • } • Now consider the following code: for (int i=0; i < 3; i++) new Piggybank( );
The constructor method is a suitable place for putting in the necessary code for initializing an object when it is being created. • Constructors are not allowed to return any value at the end of their execution. In fact, constructors do not have a return type. • public Piggybank( ) { • cents = 0; • owner = null; • }
Another restriction: the name of a constructor must be the same as the name of the class. class Piggybank { … } • public Piggybank( ) { • cents = 0; • owner = null; • }
Constructors can be parameterized. For an object to execute a constructor with parameters, the required parameters need to be passed when that object is created.
Contoh: class Piggybank { private int cents; private String owner; public Piggybank(int amt, String name) { cents = amt; owner = name; } public void deposit(int amt) { cents += amt; } public void withdraw(int amt) { cents -= amt; } }
: Piggybank cents 100 owner “Raziq” • An example of creating a Piggybank object: Piggybank pb = new Piggybank(100,“Raziq”); • public Piggybank(int amt, String name) { • cents = amt; • owner = name; • }
Each class must have at least one constructor method. • If no constructors are defined for a class, the Java compiler will automatically insert a default constructor. • The default constructor inserted will be parameterless and has an empty body.
Example: class Account { private String acctNo; private boolean active; private String owner; public Account(String nbr, String name) { acctNo = nbr; owner = name; active = false; } public void displayInfo( ) { System.out.println(“Account number: "+acctNo); System.out.println(“Owner: "+owner); System.out.print("Status: "); if (!active) System.out.print(“NOT "); System.out.println("ACTIVE"); } }
class Application { public static void main(String[ ] args) { Account acct; acct = new Account("010-99333-03", "Nada Asyiqin"); acct.displayInfo( ); } }
Method Overloading class Form{ • Consider the following program code: private int length; private char chr; • public Form(int lgth, char c) { • length = lgth; • chr = c; • } • private void displayBody(char c) { • for (int i=0; i < length; i++) • System.out.print(c); • }
private void displayHead() { • System.out.print(":>"); • } • public void displayDefault() { • displayBody(chr); • displayHead(); • } • public void displayDiffChar(char c) { • displayBody(c); • displayHead(); • } • public void displayVarLgth(int factor, char c) { • for (int i=0; i < factor; i++) • displayBody(c); • displayHead(); • } }
: Form length 3 chr ‘x’ class Application { } • public static void main(String[] args) { • Form form = new Form(3, 'x'); • form.displayDefault(); • System.out.println(); • form.displayDiffChar('*'); • System.out.println(); • form.displayVarLgth(3, '='); • } • The output: • xxx:> • ***:> • = = = = = = = = = :>
The tasks performed by the methods displayDefault(), displayDiffChar() and displayVarLgth()are basically similar i.e. to display a Formobject. Is it possible to use the same name for all of those methods? • This is allowable in Java because of its support for method overloading. Overloading a method means using the same name for more than one method in a class definition.
Method Overloading class Form{ • The program code after method overloading: private int length; private char chr; • public Form(int lgth, char c) { • length = lgth; • chr = c; • } • private void displayBody(int c) { • for (int i=0; i < length; i++) • System.out.print(c); • }
private void displayHead() { • System.out.print(":>"); • } • public void display() { • displayBody(chr); • displayHead(); • } method overloading applied • public void display(char c) { • displayBody(c); • displayHead(); • } • public void display(int factor, char c) { • for (int i=0; i < factor; i++) • displayBody(c); • displayHead(); • } }
: Form length 3 chr ‘x’ class Application { } • public static void main(String[] args) { • Form form = new Form(3, 'x'); • form.display(); • System.out.println(); • form.display('*'); • System.out.println(); • form.display(3, '='); • } • public void display () { • displayBody(chr); • displayHead(); • } • public void display (char c) { • displayBody(c); • displayHead(); • } • public void display(int factor, char c) { • for (int i=0; i < factor; i++) • displayBody(c); • displayHead(); • }
Example 2: • The println()method is actually overloaded in the PrintStreamclass. int pbhInt; double pbhDbl; System.out.println("UKM"); System.out.println('X'); System.out.println(pbhInt); System.out.println(pbhDbl);
How is Java able to differentiate methods with the same name? It differentiates those methods based on the type and sequence of their parameters.
class Test { } • public void doThis(double x) { • System.out.println(“1stMethod"); • } • public void doThis(float x) { • System.out.println(“2ndMethod"); • } • public void doThis(double x, String y) { • System.out.println(“3rdMethod"); • } • public static void main(String[] args) { • Test t = new Test(); • t.doThis(3.3); • t.doThis(3.3F); • t.doThis('k'); • t.doThis(5.2, “try"); • // t.doThis(“ERROR"); • } No match 1stMethod 2ndMethod 2ndMethod 3rdMethod Automatic casting occurs char => int => float
The output: 1stMethod 2ndMethod 2ndMethod 3rdMethod • Note that the message in the commented statement in the main( )method does not match with any of the doThis()methods in the Testclass.
Note also that t.doThis('k'); results in the execution of the doThis(float)method. Since there is no doThis(char) method defined in the Testclass, Java automatically casts the actual parameter to find the closest match. doThis(char) => doThis(int) => doThis(float)
It is common to define classes with overloaded constructor methods. This provides their users with more than one way of creating instances.
Constructor methods are overloaded class Rectangle { … } private int width, height; • public Rectangle() { • width = 1; • height = 1; • } • public Rectangle(int size) { • width = size; • height = size; • } • public Rectangle(int w, int h) { • width = w; • height = h; • } Example 1:
Executes second constructor class Application { } • public static void main(String[] args) { • Rectangle r1 = new Rectangle(5); • Rectangle r2 = new Rectangle(3, 4); • Rectangle r3 = new Rectangle(); • ... • } Executes third constructor Executes first constructor
Example 2: • The Date class provided in the Java class library defines a number of constructors including the following: public Date(); public Date(long milliseconds); public Date(int year, int month, int day); public Date(int year, int month, int day, int hour, int minute); public Date(int year, int month, int day, int hour, int minute, int second);