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.
26
Embed
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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.
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
3
Another Constructor Example class Student { private String name; // Student's name. private double test1, test2, test3; // Grades on three tests.
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);
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).
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
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" );
Different outputs, because each Time2 reference was instantiated with a different constructor
Different outputs, because each Time2 reference was instantiated
with a different constructor
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
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
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
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
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");
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;
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 );
Outline20
Increment.java
36 }37 38 } // end class Increment
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;
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.
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
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, .....)
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