32
Spring 2008 Mark Fontenot [email protected] CSE 1341 Principles of Computer Science I Note Set 8

Spring 2008 Mark Fontenot [email protected] CSE 1341 Principles of Computer Science I Note Set 8

Embed Size (px)

Citation preview

Spring 2008

Mark [email protected]

CSE 1341Principles of Computer Science I

Note Set 8

Note Set 8 Overview

Objects in depthInterface of a classReview of Access to membersthe this referenceOverloaded ConstructorsDefault and No Arg constructors

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

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 variablesshould perform error checking – keeps object in consistent state

more elegant error checking to come

Time Classpublic 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.

Time1Testpublic 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:00Standard Time: 12:00:00 AM

Time1Testpublic 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

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.

The this object referenceEvery 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 refferencedthrough the this reference variable.

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

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 insteadof the parameters.

Overloaded constructors

public class Test { private int a; public Test() { this(0); }

public Test(int x) { a = x; }}

Call another constructor usingthe this reference.Calling another constructor with thismust be the 1st line in the body of theconstructor

Concentrate init logic in one method

See Fig 8.5 – Time2.java

Special constructor

public class Time2 { //Declarations

public Time2 (Time2 time){ this(time.getHour(), time.getMinute(), time.getSecond()); } }

Accessing sets and gets in the classReusability – 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).

Set and Get vs. public dataWhy not just make the instance variables public?

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

Software Reusability No need to “reinvent the wheel”

Allows software developers to use Java API or other APIs that are well tested

Rapid Application DevelopmentRADSoftware reusability speeds the development of high-quality

software

Composition – has-aWhen 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

has-a & composition Car has-a motormotor has-a transmissionStudent has-a addressaddress has-a streetframe has-a panel

Other examples?

Garbage Collection in JavaWhen 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 useGarbage collector does not necessarily release other system

resources such as files, etc.System.gc(); //asks for GC to happencan 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

Static class membersTwo types of members of a class

Static variable ONLY one no matter how many objects of a type are allocatedon a PER-CLASS basis

Instance variablesOne for EVERY object that is instantiatedon a PER-OBJECT basis

public class Test { private int x; private int y; private static int count; //methods}

//Before the two object are allocatedTest obj1;Test obj2;

Memory

obj1

obj2

x

y

x

ycount

Count exists in memorybefore any objects of typeTest are allocated

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}

Static MethodsStatic 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 senseAccess 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; }}

InheritanceOne of the cornerstones of OOPA type of software re-useA 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)

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

subclass superclass

JPanel

MultiplicationPanel

Class Object Object is the top level class in every inheritance hierarchyEvery 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

Some Inheritance ExamplesStudent

UndergradStudent Grad Student

Circle Triangle Rectangle

Shape

BankAccount

CheckingAccount SavingsAccount

Codepublic 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

Codepublic 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

gpas

s has the data from both Personand Student

Any public member from Person or Student canbe called on object s.

Protected accesspublic – can be seen/accessed/called from outside the classprivate – can only be seen/accessed/called from inside the

classprotected – 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? ____________

Code – Private Namepublic 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

Code – Protected Namepublic 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 subclassand a public member of the superclass is a public member of the subclass.