1 / 34

OO Support in Java: Classes (Part 2)

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;

Télécharger la présentation

OO Support in Java: Classes (Part 2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OO Support in Java: Classes (Part 2)

  2. INTRODUCTION • The following topics will be discussed: • Constructor Methods • Method Overloading

  3. 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"); } }

  4. 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.

  5. Can object initialization be done during object creation? • Two common ways of initializing attributes during object creation: • Via instance variable initializers • Via constructor methods

  6. 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; } }

  7. : 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( );

  8. 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

  9. 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.

  10. : 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( );

  11. 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; • }

  12. 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; • }

  13. 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.

  14. 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; } }

  15. : 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; • }

  16. 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.

  17. 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"); } }

  18. class Application { public static void main(String[ ] args) { Account acct; acct = new Account("010-99333-03", "Nada Asyiqin"); acct.displayInfo( ); } }

  19. 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); • }

  20. 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(); • } }

  21. : 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:> • ***:> • = = = = = = = = = :>

  22. 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.

  23. 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); • }

  24. 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(); • } }

  25. : 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(); • }

  26. 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);

  27. How is Java able to differentiate methods with the same name? It differentiates those methods based on the type and sequence of their parameters.

  28. 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

  29. 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.

  30. 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)

  31. It is common to define classes with overloaded constructor methods. This provides their users with more than one way of creating instances.

  32. 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:

  33. 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

  34. 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);

More Related