Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8.

Similar presentations


Presentation on theme: "Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8."— Presentation transcript:

1 Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8

2 Note Set 8 Overview Objects in depth Interface of a class Review of Access to members the this reference Overloaded Constructors Default and No Arg constructors

3 Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } Public Interface Time is a class. Objects of type Time provide a service. The services are indicated by the public interface

4 Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } methods that modify private instance variables should perform error checking – keeps object in consistent state more elegant error checking to come methods that modify private instance variables should perform error checking – keeps object in consistent state more elegant error checking to come

5 Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } Every object has a toString() method (implicitly or explicity) Called implicitly whenever a Time object needs to be converted to a string, such as in a printf. Every object has a toString() method (implicitly or explicity) Called implicitly whenever a Time object needs to be converted to a string, such as in a printf.

6 Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.setTime(13, 27,6); System.out.print(“Initial Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Initial Standard Time: “); System.out.println(time.toString()); System.out.println(); time.setTime(99, 99, 99); System.out.print(“Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Standard Time: “); System.out.println(time.toString()); } Initial Universal Time: 13:27:06 Initial Standard Time: 1:27:06 PM Universal Time: 00:00:00 Standard Time: 12:00:00 AM Initial Universal Time: 13:27:06 Initial Standard Time: 1:27:06 PM Universal Time: 00:00:00 Standard Time: 12:00:00 AM

7 Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.setTime(99, 99, 99); System.out.print(“Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Standard Time: “); System.out.println(time.toString()); } Classes simplify the programming here. We don’t care how this happens, we just know it does. Details are abstracted away in the object’s implementation Clients usually care about what the class does but not how it does it Clients are not affected by a change in implementation. Interfaces change less frequently than implementation You might find a more efficient way of doing this or that later, but you don’t want to break code that depends on the fact that you can do this or that in some wha

8 Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.hour = 7; time.minute = 15; time.second = 30; } Illegal – cannot access the private data members directly. Must go through the interface methods that are supplied by the class.

9 The this object reference Every object can access a reference to itself with keyword this. When a non-static method is called, the calling object is passed implicitly to the method Time t = new Time(); t.setTime( 12, 13, 14); System.out.println( t.toString() ); t is passed to the toString method implicitly. in toString, it can be refferenced through the this reference variable.

10 this public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } How can these variables be accessed if they have no declaration? They were declared when the object that called this method was instantiated. They are referring to those variables that are part of the invoking object. public void setTime(int h, int m, int s) { this.hour = ((h >= 0 && h < 24) ? h : 0); this.minute = ((m >= 0 && m < 60) ? m : 0); this.second = ((s >= 0 && s < 60) ? m : 0); } Equivalent

11 Using this to avoid shadowing public class Test { private int a, b, c; public void foo(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } Accesses the instance data members instead of the parameters.

12 Overloaded constructors public class Test { private int a; public Test() { this(0); } public Test(int x) { a = x; } Call another constructor using the this reference. Calling another constructor with this must be the 1 st line in the body of the constructor Concentrate init logic in one method See Fig 8.5 – Time2.java

13 Special constructor public class Time2 { //Declarations public Time2 (Time2 time){ this(time.getHour(), time.getMinute(), time.getSecond()); } }

14 Accessing sets and gets in the class Reusability – concentrate logic to set value and get value in one area – the accessors and mutators. Consider if time was represented as an int holding number of seconds since midnight rather than 3 ints. if you have many time objects, this can be a space saver – from 12 bytes down to 4. If all conversion is done in set and get, then don’t have to worry about modifying the same logic twice (or getting it wrong twice).

15 Set and Get vs. public data Why not just make the instance variables public?

16 You might have noticed… Classes interact in your programs An instance method might receive an object as a parameter (even just at string) Once class might have an object of a different type as an instance variable public class MyClass { private Point x; A class might absorb the functionality of another class and add new attributes and functionality You make copious use of the Java API that contains a vast amount of pre-written, well-tested code

17 Software Reusability No need to “reinvent the wheel” Allows software developers to use Java API or other APIs that are well tested Rapid Application Development RAD Software reusability speeds the development of high-quality software

18 Composition – has-a When a class has references to objects of other classes as members. Great example of software re-use public class CardShoe { private Card [] cards; //other members } A CardShoe Object contains an array of Card objects CardShoe has access to all of the public members of the Card class. CardShoe does not have access to any of the private members of Card CardShoe HAS-A card

19 has-a & composition Car has-a motor motor has-a transmission Student has-a address address has-a street frame has-a panel Other examples?

20 Garbage Collection in Java When you allocate new objects, space is used in RAM as well as other system resources (network, files, etc). What releases these resources? JVM performs Garbage Collection to reclaim memory occupied by objects that are no longer in use Garbage collector does not necessarily release other system resources such as files, etc. System.gc(); //asks for GC to happen can use the finalize method in a class to clean-up allocated or reserved resources. Called by GC if GC attempts to reclaim an object – no guarantees though – GC might not actually run

21 Static class members Two types of members of a class Static variable ONLY one no matter how many objects of a type are allocated on a PER-CLASS basis Instance variables One for EVERY object that is instantiated on a PER-OBJECT basis public class Test { private int x; private int y; private static int count; //methods } //Before the two object are allocated Test obj1; Test obj2; Memory obj1 obj2 x x y y x x y y count Count exists in memory before any objects of type Test are allocated

22 When to Static??? When to Instance??? If every object of a particular type needs access to the same exact piece(s) of data, then make it static. If a division of employees makes produces more than 500K in profit for the company, then they get a 10% bonus based on salary public class Division { //An Employee obj Contains vital info including salary private Employee[] emps; public static double totalProfitForDiv; //other methods }

23 Static Methods Static Methods have access to static members (other static methods or static data) Cannot access instance variables – because they aren’t instance methods – doesn’t make sense Access using name of class and dot (.) public class Division { //An Employee obj Contains vital info including salary private Employee[] emps; public static double totalProfitForDiv; //other methods public static double getTotalProfit(){ //This method cannot access any element of emps return totalProfitForDiv; }

24 Inheritance One of the cornerstones of OOP A type of software re-use A new class is created by absorbing the members of an existing class and adding to or modifying those absorbed members Instead of the has-a relationship, Inheritance involves the is-a relationship. MultiplicationPanel is-a JPanel (has-a doesn’t make sense)

25 Terminology subclass vs superclass subclass inherits the members of the super class public class MultiplicationPanel extends JPanel In an is-a relationship, a subclass object may be treated as an object of its superclass. subclasssuperclass JPanel MultiplicationPanel

26 Class Object Object is the top level class in every inheritance hierarchy Every class extends Object implicitly if it doesn’t extend another class explicitly public class Person{ private String name; private String address; } Object Person public class Employee extends Person{ private float salary; } Object Person Employee

27 Some Inheritance Examples Student UndergradStudent Grad Student Circle Triangle Rectangle Shape BankAccount CheckingAccount SavingsAccount

28 Code public class Person { private String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } extends indicates inheritance Student has everything from person plus whatever new “stuff” it adds

29 Code public class Person { private String name; public void setName(String s){ name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } In Main : Student s = new Student(); name gpa s s has the data from both Person and Student Any public member from Person or Student can be called on object s.

30 Protected access public – can be seen/accessed/called from outside the class private – can only be seen/accessed/called from inside the class protected – can be only be seen/accessed/called from inside the class AND from subclasses ?1 – Does a subclass have access to directly modify a private instance variable of the superclass? _____________ ?2 – Does a subclass have access to directly modify a protected instance variable of the superclass? ____________

31 Code – Private Name public class Person { private String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } public void setData (String s, float g) { name = s; gpa = g; } method setData does not have access to private data member name from Person

32 Code – Protected Name public class Person { protected String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person { private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } public void setData (String s, float g) { name = s; gpa = g; } Now this is OK because name has protected visibility – can be directly access by subclasses Inherited members maintain their visibility in subclasses. So – a protected member of the superclass is a protected member of the subclass and a public member of the superclass is a public member of the subclass.


Download ppt "Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8."

Similar presentations


Ads by Google