Download presentation
Presentation is loading. Please wait.
Published byLouisa Fleming Modified over 9 years ago
1
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
2 Constructor Example class 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
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; }
4
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
5
5 Test Program public 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()); } Output John:80.83333333333333 Peter: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);
6
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).
7
Outline 7 Time2.java Lines 16-19 Default constructor has no arguments Lines 23-26 Overloaded constructor has one int argument Lines 30-33 Second overloaded constructor has two int arguments 1 // Fig. 8.6: Time2.java 2 // Time2 class definition with overloaded constructors. 3 4 5 // Java core packages 6 import java.text.DecimalFormat; 7 8 public class Time2 { 9 private int hour; // 0 - 23 10 private int minute; // 0 - 59 11 private int second; // 0 - 59 12 13 // Time2 constructor initializes each instance variable 14 // 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 second 22 // defaulted to 0 23 public Time2( int h ) 24 { 25 setTime( h, 0, 0 ); 26 } 27 28 // Time2 constructor: hour and minute supplied, second 29 // defaulted to 0 30 public Time2( int h, int m ) 31 { 32 setTime( h, m, 0 ); 33 } 34
8
Outline 8 Time2.java Lines 36-39 Third overloaded constructor has three int arguments Lines 42-45 Fourth overloaded constructor has Time2 argument 35 // Time2 constructor: hour, minute and second supplied 36 public Time2( int h, int m, int s ) 37 { 38 setTime( h, m, s ); 39 } 40 41 // Time2 constructor: copy constructor 42 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 format 57 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 format 67 public String toString() 68 { 69 DecimalFormat twoDigits = new DecimalFormat( "00" );
9
Outline 9 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
10
Outline 10 TimeTest4.java Line 15 Declare six references to Time2 objects Lines 17-22 Instantiate each Time2 reference using a different constructor 1 // Fig. 8.7: TimeTest4.java 2 // Using overloaded constructors 3 4 // Java extension packages 5 import javax.swing.*; 6 7 8 9 10 public class TimeTest4 { 11 12 // test constructors of class Time2 13 public static void main( String args[] ) 14 { 15 Time2 t1, t2, t3, t4, t5, t6; 16 17 t1 = new Time2(); // 00:00:00 18 t2 = new Time2( 2 ); // 02:00:00 19 t3 = new Time2( 21, 34 ); // 21:34:00 20 t4 = new Time2( 12, 25, 42 ); // 12:25:42 21 t5 = new Time2( 27, 74, 99 ); // 00:00:00 22 t6 = new Time2( t4 ); // 12:25:42 23 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
11
Outline 11 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
12
Outline 12 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
13
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
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
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
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
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
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;
19
Outline 19 Increment.java Line 15 final keyword declares INCREMENT as constant Line 32 final variable INCREMENT must be initialized before using it 1 // Fig. 8.11: Increment.java 2 // Initializing a final variable 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class Increment extends JApplet 12 implements ActionListener { 13 14 private int count = 0, total = 0; 15 private final int INCREMENT = 5; // constant variable 16 17 private JButton button; 18 19 // set up GUI 20 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 button 30 public void actionPerformed( ActionEvent actionEvent ) 31 { 32 total += INCREMENT; 33 count++; 34 showStatus( "After increment " + count + 35 ": total = " + total );
20
Outline 20 Increment.java 36 } 37 38 } // end class Increment
21
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
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
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
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
25 // TestStatic.java class Employee { static int maxNum = 20000; private int num; public int getEmpNum() { return num; } public void setEmpNum(int newNum) { if (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 TestStatic maxNum of emp1 : 20000 maxNum of emp2 : 20000 maxNum of emp2 : 99999
26
26 Class (Static) Members Object1 Object2 Object3 num MaxNum
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.