1 chapter 3 – object-based programming 2 initializing class objects: constructors class...

26
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables of a class object. Same name as class No return type (don’t declar void) or return statement Cannot be called directly Called when instantiating object of that class· If no constructor is defined by the programmer, a default "do-nothing" constructor is created for you. Java does not provide a default constructor if the class define a constructor of its own.

Upload: louisa-fleming

Post on 18-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

1

Chapter 3 – Object-Based Programming 2

Initializing Class Objects: Constructors

• Class constructor is a specical method to initialise instance variables of a class object.

– Same name as class– No return type (don’t declar void) or return statement – Cannot be called directly– Called when instantiating object of that class·– If no constructor is defined by the programmer, a default "do-nothing"

constructor is created for you. – Java does not provide a default constructor if the class define a constructor

of its own.

Page 2: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

2

Constructor Exampleclass Employee1 { private int num;

public Employee1(int newNum) { num = newNum; // call setNum() is better, why? }

public int getNum() { return num; } public void setNum(int newNum) { num = newNum; }}

class PrintEmployee5 { public static void main(String[] args) { Employee1 emp; emp = new Employee1(71623); System.out.println(emp.getNum()); }}

>java PrintEmployee5

71623

Page 3: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

3

Another Constructor Example class Student { private String name; // Student's name. private double test1, test2, test3; // Grades on three tests.

public Student(String inName, double inTest1, double inTest2, double inTest3) { setName(inName); setTest1(inTest1); setTest2(inTest2); setTest3(inTest3); }

// Getter and Setter methods .... public void setName(String inName) { name = inName; }

public String getName() { return name; }

public void setTest1(double inTest1) { test1 = inTest1; }

public double getTest1() { return test1; }

Page 4: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

4

Another Constructor Example public void setTest2(double inTest2) { test2 = inTest2; }

public double getTest2() { return test1; }

public void setTest3(double inTest3) { test3 = inTest3; }

public double getTest3() { return test3; }

double getAverage() { // compute average test grade return (test1 + test2 + test3) / 3; }

} // end of class Student

Page 5: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

5

Test Programpublic class TS { public static void main(String s[]) { Student stud1, stud2; stud1 = new Student("John", 80.5, 78.5, 83.5); stud2 = new Student("Peter", 30, 0, 0);

System.out.println(stud1.getName() + ":" + stud1.getAverage()); System.out.println(stud2.getName() + ":" + stud2.getAverage()); }}

OutputJohn:80.83333333333333Peter:10.0

Old Version stud1 = new Student(); stud1.setName("John"); stud1.setTest1(80.5); stud1.setTest2(78.5); stud1.setTest3(83.5);

stud2 = new Student(); stud2.setName("Peter"); stud2.setTest1(30);

Page 6: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

6

Using Overloaded Constructors

• Overloaded constructors– Methods (in same class) may have same name– Must have different parameter lists

• Examples in Java– String– JButton– .......

• The following example illustrate the use of overloaded constructor. Setting a time value by providing hour, minute (optional) and second (optional).

Page 7: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline7

Time2.java

Lines 16-19Default constructor has no arguments

Lines 23-26Overloaded constructor has one int argument

Lines 30-33Second overloaded constructor has two int arguments

1 // Fig. 8.6: Time2.java2 // Time2 class definition with overloaded constructors.3 4 5 // Java core packages6 import java.text.DecimalFormat; 7 8 public class Time2 {9 private int hour; // 0 - 2310 private int minute; // 0 - 5911 private int second; // 0 - 5912 13 // Time2 constructor initializes each instance variable14 // to zero. Ensures that Time object starts in a 15 // consistent state.16 public Time2() 17 { 18 setTime( 0, 0, 0 ); 19 }20 21 // Time2 constructor: hour supplied, minute and second22 // defaulted to 023 public Time2( int h ) 24 { 25 setTime( h, 0, 0 ); 26 }27 28 // Time2 constructor: hour and minute supplied, second29 // defaulted to 030 public Time2( int h, int m ) 31 { 32 setTime( h, m, 0 );33 }34

Page 8: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline8

Time2.java

Lines 36-39Third overloaded constructor has three int arguments

Lines 42-45Fourth overloaded constructor has Time2 argument

35 // Time2 constructor: hour, minute and second supplied36 public Time2( int h, int m, int s ) 37 { 38 setTime( h, m, s ); 39 }40 41 // Time2 constructor: copy constructor42 public Time2( Time2 time )43 {44 setTime( time.hour, time.minute, time.second );45 }46 47 // Set a new time value using universal time. Perform 48 // validity checks on data. Set invalid values to zero.49 public void setTime( int h, int m, int s )50 {51 hour = ( ( h >= 0 && h < 24 ) ? h : 0 );52 minute = ( ( m >= 0 && m < 60 ) ? m : 0 );53 second = ( ( s >= 0 && s < 60 ) ? s : 0 );54 }55 56 // convert to String in universal-time format57 public String toUniversalString()58 {59 DecimalFormat twoDigits = new DecimalFormat( "00" );60 61 return twoDigits.format( hour ) + ":" +62 twoDigits.format( minute ) + ":" +63 twoDigits.format( second );64 }65 66 // convert to String in standard-time format67 public String toString()68 {69 DecimalFormat twoDigits = new DecimalFormat( "00" );

Page 9: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline9

Time2.java

70 71 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) +72 ":" + twoDigits.format( minute ) +73 ":" + twoDigits.format( second ) +74 ( hour < 12 ? " AM" : " PM" );75 }76 77 } // end class Time2

Page 10: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline10

TimeTest4.java

Line 15Declare six references to Time2 objects

Lines 17-22Instantiate each Time2 reference using a different constructor

1 // Fig. 8.7: TimeTest4.java2 // Using overloaded constructors3 4 // Java extension packages5 import javax.swing.*;6 7 8 9 10 public class TimeTest4 {11 12 // test constructors of class Time213 public static void main( String args[] )14 {15 Time2 t1, t2, t3, t4, t5, t6;16 17 t1 = new Time2(); // 00:00:0018 t2 = new Time2( 2 ); // 02:00:0019 t3 = new Time2( 21, 34 ); // 21:34:0020 t4 = new Time2( 12, 25, 42 ); // 12:25:4221 t5 = new Time2( 27, 74, 99 ); // 00:00:0022 t6 = new Time2( t4 ); // 12:25:4223 24 String output = "Constructed with: " +25 "\nt1: all arguments defaulted" +26 "\n " + t1.toUniversalString() +27 "\n " + t1.toString();28 29 output += "\nt2: hour specified; minute and " +30 "second defaulted" +31 "\n " + t2.toUniversalString() +32 "\n " + t2.toString();33

Page 11: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline11

TimeTest4.java

34 output += "\nt3: hour and minute specified; " +35 "second defaulted" +36 "\n " + t3.toUniversalString() +37 "\n " + t3.toString();38 39 output += "\nt4: hour, minute, and second specified" +40 "\n " + t4.toUniversalString() +41 "\n " + t4.toString();42 43 output += "\nt5: all invalid values specified" +44 "\n " + t5.toUniversalString() +45 "\n " + t5.toString();46 47 output += "\nt6: Time2 object t4 specified" +48 "\n " + t6.toUniversalString() +49 "\n " + t6.toString();50 51 JOptionPane.showMessageDialog( null, output,52 "Demonstrating Overloaded Constructors",53 JOptionPane.INFORMATION_MESSAGE );54 55 System.exit( 0 );56 }57 58 } // end class TimeTest4

Page 12: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline12

TimeTest4.java

Different outputs, because each Time2 reference was instantiated with a different constructor

Different outputs, because each Time2 reference was instantiated

with a different constructor

Page 13: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

13

More Examples• Explain why the following programs are incorrect.

class Employee { private int num;

public void Employee(int newNum) { num = newNum; }

public int getNum() { return num; } public void setNum(int newNum) { num = newNum; }}

class TE { public static void main(String[] args) { Employee emp; emp = new Employee(71623); System.out.println(emp.getNum()); }}

1

Page 14: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

14

More Examples

class Employee { private int num;

public Employee(int newNum) { num = newNum; }

public int getNum() { return num; } public void setNum(int newNum) { num = newNum; }}

class TE { public static void main(String[] args) { Employee emp = new Employee(); emp.setNum(71623); System.out.println(emp.getNum()); }}

2

Page 15: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

15

More Examples

class Employee { private int num;

public Employee1(int newNum) { num = newNum; } public int getNum() { return num; } public void setNum(int newNum) { num = newNum; }

}

class TE { public static void main(String[] args) { Employee emp = new Employee1(71623); System.out.println(emp.getNum()); }}

3

Page 16: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

16

Read Only Property

• Consider the name attributes of the following Student class:

public class Student { private String name; // Student's name. public double test1, test2, test3; // Grades on three tests. Student(String theName) { name = theName; } public String getName() { return name; } public double getAverage() { return (test1 + test2 + test3) / 3; } } // end of class Student

Page 17: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

17

Read Only Property

• The name attribute cannot be modified once the object is created.

std1 = new Student("John Smith");

std2 = new Student("Mary Jones");

Page 18: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

18

Final Instance Variables

• final keyword– Indicates that variable is not modifiable

• Any attempt to modify final variable results in error

Declares variable INCREMENT as a constant

– Enforces principle of least privilege

private final int INCREMENT = 5;

Page 19: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline19

Increment.java

Line 15final keyword declares INCREMENT as constant

Line 32final variable INCREMENT must be initialized before using it

1 // Fig. 8.11: Increment.java2 // Initializing a final variable3 4 // Java core packages5 import java.awt.*;6 import java.awt.event.*;7 8 // Java extension packages9 import javax.swing.*;10 11 public class Increment extends JApplet12 implements ActionListener {13 14 private int count = 0, total = 0;15 private final int INCREMENT = 5; // constant variable16 17 private JButton button; 18 19 // set up GUI20 public void init() 21 { 22 Container container = getContentPane();23 24 button = new JButton( "Click to increment" );25 button.addActionListener( this );26 container.add( button );27 }28 29 // add INCREMENT to total when user clicks button30 public void actionPerformed( ActionEvent actionEvent )31 {32 total += INCREMENT;33 count++;34 showStatus( "After increment " + count +35 ": total = " + total );

Page 20: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

Outline20

Increment.java

36 }37 38 } // end class Increment

Page 21: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

21

Constants (Static)

• More often constants will be defined as public and static:

• public - Other classes can read the value of the constant

• static - only one copy shared by all objects, hence save memory (see next slide)

• Examples in Java - JOptionPane, String, Math, .....

public static final int INCREMENT = 5;

Page 22: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

22

Static Class Members

• Most properties, like the balance in bank account, are unique to the object, which should be stored as instance variable (attribute or data member).

• But some properties are shared among all objects of a given class. For example, the interest rate is a property shared by all saving accounts in the same bank.

• Such properties are called class member.

• Class members are defined using the keyword static. So class members are also called static members.

Page 23: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

23

Static Class Members

• static class variable– Class-wide information

• All class objects share same data

– can be accessed via class name or an object reference

• static method– can be accessed via class name or an object reference

– can access static members only (i.e. CANNOT read non-static instance variables or call non-static methods.)

• non-static method– can access both static and non-static variables

Page 24: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

24

Static Class Members

• When should a variable be declared as static?– data will be shared by all classes (e.g. Employee Counter,

Account Interest, constants)

– it saves memory and is easy to maintain

• When should a method be declared as static?– the method will be used as an utility, not operates on an

object (e.g. main, Math.sqrt, Math.sin, .....)

Page 25: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

25

// TestStatic.java

class Employee { static int maxNum = 20000; private int num; public int getEmpNum() { return num; } public void setEmpNum(int newNum) { if (newNum<=maxNum && newNum >1) num = newNum; }}

class TestStatic { public static void main(String[] args) { Employee emp1 = new Employee(); Employee emp2 = new Employee(); System.out.println(“maxNum of emp1 : " + emp1.maxNum); System.out.println(“maxNum of emp2 : " + emp2.maxNum); emp1.maxNum = 99999; System.out.println("\nmaxNum of emp2 : " + emp2.maxNum); }}

>java TestStaticmaxNum of emp1 : 20000maxNum of emp2 : 20000

maxNum of emp2 : 99999

Page 26: 1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables

26

Class (Static) Members

Object1

Object2

Object3

num

num

num

MaxNum