object class

14
Object class Object class

Upload: channer

Post on 06-Jan-2016

53 views

Category:

Documents


3 download

DESCRIPTION

Object class. Object class. All objects extend (inherit from) Object (see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html ). The Object class has a number of especially interested methods (that are inherited by our classes) such as: clone equals getClass toString. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Object class

Object classObject class

Page 2: Object class

Object classObject class

All objects extend (inherit from) Object All objects extend (inherit from) Object (see (see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html).).

The Object class has a number of The Object class has a number of especially interested methods (that are especially interested methods (that are inherited by our classes) such as:inherited by our classes) such as:• cloneclone• equalsequals• getClassgetClass• toStringtoString

Page 3: Object class

Invoking the base version of an Invoking the base version of an overridden methodoverridden method

Example:Example:

public String toString ( ) {public String toString ( ) {

return super.toString() + “blah blah blah”;return super.toString() + “blah blah blah”;

}}

Page 4: Object class

instanceof operatorinstanceof operator

Another boolean operator like ==, !Another boolean operator like ==, !=, <, >=, …=, <, >=, …

SyntaxSyntax• object instanceof Class_Nameobject instanceof Class_Name• True if object is of type Class_Name (or True if object is of type Class_Name (or

true if object is a descendent of true if object is a descendent of Class_name).Class_name).

• False, otherwise.False, otherwise.

Page 5: Object class

instanceof operatorinstanceof operator (x instanceof Object)(x instanceof Object)

• True for all objectsTrue for all objects Recall EmployeeRecall Employee

• HourlyEmployeeHourlyEmployee• SalariedEmployeeSalariedEmployee• Ex. 1Ex. 1

SalariedEmployee x = new SalariedEmployee();SalariedEmployee x = new SalariedEmployee(); (x instanceof Object)(x instanceof Object) //true//true (x instanceof Employee)(x instanceof Employee) //true//true (x instanceof SalariedEmployee)(x instanceof SalariedEmployee) //true//true (x instanceof String)(x instanceof String)

• Won’t compile. “Inconvertible types.”Won’t compile. “Inconvertible types.” (x instanceof HourlyEmployee)(x instanceof HourlyEmployee)

• Won’t compile. “Inconvertible types.”Won’t compile. “Inconvertible types.”

Page 6: Object class

instanceof operatorinstanceof operator

Example:Example:Integer i = new Integer(12);Integer i = new Integer(12);

Object o = i;Object o = i;

//Won’t compile://Won’t compile:

//System.out.println( (i instanceof String) );//System.out.println( (i instanceof String) );

//OK. Compiles. Runs. Returns false://OK. Compiles. Runs. Returns false:

System.out.println( (o instanceof String) ); //falseSystem.out.println( (o instanceof String) ); //false

System.out.println( (o instanceof Object) ); //trueSystem.out.println( (o instanceof Object) ); //true

System.out.println( (o instanceof Integer) ); //trueSystem.out.println( (o instanceof Integer) ); //true

Page 7: Object class

The instanceof operator and the The instanceof operator and the getClass methodgetClass method

Recall that the instanceof operator is true Recall that the instanceof operator is true “up and down” the inheritance hierarchy.“up and down” the inheritance hierarchy.

We need something more specific.We need something more specific. getClass returns a representation of the getClass returns a representation of the

class that was used with new to create the class that was used with new to create the objectobject• Can be compared with == and !=Can be compared with == and !=• Ex.Ex.

if (object1.getClass() == object2.getClass())if (object1.getClass() == object2.getClass())System.out.println( “same class.” );System.out.println( “same class.” );

elseelseSystem.out.println( “not the same class.” );System.out.println( “not the same class.” );

Page 8: Object class

The proper way to define equals()The proper way to define equals()

Recall that everything is a descendent Recall that everything is a descendent of Object.of Object.

The equals method for Object is The equals method for Object is defined as:defined as:public boolean equals ( Object otherObject )public boolean equals ( Object otherObject )• To override this method, our equals To override this method, our equals

method most be rewritten with the above method most be rewritten with the above heading. (Otherwise, Employee has both heading. (Otherwise, Employee has both equals methods.)equals methods.)

Page 9: Object class

A better equals methodA better equals method

public boolean equals ( Object other ) {public boolean equals ( Object other ) {if (other==null) {if (other==null) {

return false;return false;} else if (getClass() != other.getClass()) {} else if (getClass() != other.getClass()) {

return false;return false;} else {} else {

Employee tmp = (Employee)other;Employee tmp = (Employee)other; // // what’s this called? what’s this called?

return ( name.equals( tmp.name )return ( name.equals( tmp.name )&& hireDate.equals( tmp.hireDate ) );&& hireDate.equals( tmp.hireDate ) );

}}}}

Why can’t we use instanceof instead of getClass?Why can’t we use instanceof instead of getClass?

Page 10: Object class

ProblemProblem Define a class named Payment that contains a member Define a class named Payment that contains a member

variable of type double that stores the amount of the variable of type double that stores the amount of the payment and appropriate accessor and mutator methods. payment and appropriate accessor and mutator methods. Also create a method named paymentDetails that outputs Also create a method named paymentDetails that outputs an English sentence to describe the amount of the an English sentence to describe the amount of the payment.payment.

Next, define a class named CashPayment that is derived Next, define a class named CashPayment that is derived from Payment. This class should redefine the from Payment. This class should redefine the paymentDetails method to indicate that the payment is in paymentDetails method to indicate that the payment is in cash. Include appropriate constructor(s).cash. Include appropriate constructor(s).

Define a class named CreditCardPayment that is derived Define a class named CreditCardPayment that is derived from Payment. This class should contain member variables from Payment. This class should contain member variables for the name on the card, expiration date, and credit card for the name on the card, expiration date, and credit card number. Include appropriate constructor(s). Finally, number. Include appropriate constructor(s). Finally, redefine the paymentDetails method to include all credit redefine the paymentDetails method to include all credit card information in the printout.card information in the printout.

Create a main method that creates at least two Create a main method that creates at least two CashPayment and two CreditCardPayment objects with CashPayment and two CreditCardPayment objects with different values and calls paymentDetails for each.different values and calls paymentDetails for each.

Page 11: Object class

ProblemProblem Define a classDefine a class named Document that contains a member variable of named Document that contains a member variable of

type String named type String named texttext that stores any textual content for the that stores any textual content for the document. Create a method named toString that returns the text document. Create a method named toString that returns the text field. Also include a method to set this value.field. Also include a method to set this value.

Next, Next, define a classdefine a class for Email that is derived from Document and for Email that is derived from Document and includes member variables for the sender, recipient, and subject of includes member variables for the sender, recipient, and subject of an email message. Implement appropriate accessor and mutator an email message. Implement appropriate accessor and mutator methods. The body of the email message should be stored in the methods. The body of the email message should be stored in the inherited variable text. Redefine the toString method to concatenate inherited variable text. Redefine the toString method to concatenate all text fields.all text fields.

Similarly, Similarly, define a classdefine a class for File that is derived from Document and for File that is derived from Document and includes a member variable for the pathname. The textual contents includes a member variable for the pathname. The textual contents of the file should be stored in the inherited variable text. Redefine of the file should be stored in the inherited variable text. Redefine the toString method to concatenate all text fields.the toString method to concatenate all text fields.

Finally, create several sample objects of type Email and File in you Finally, create several sample objects of type Email and File in you main method. Test your objects by passing them to the following main method. Test your objects by passing them to the following method that returns true if the object contains the specified keyword method that returns true if the object contains the specified keyword in the text property.in the text property.

public static boolean ContainKeyword (public static boolean ContainKeyword ( Document docObject,Document docObject,String keyword ) {String keyword ) {

if (docObject.toString().indexOf(keyword,0) >= 0)if (docObject.toString().indexOf(keyword,0) >= 0) return true;return true;return false;return false;

}}

Page 12: Object class

ProblemProblem Create a class called Vehicle that has the Create a class called Vehicle that has the

manufacturer’s name (type String), number of manufacturer’s name (type String), number of cylinders in the engine (type int), and owner cylinders in the engine (type int), and owner (type Person assumed to be already defined). (type Person assumed to be already defined). Then, create a class called Truck that is derived Then, create a class called Truck that is derived from Vehicle and has the following additional from Vehicle and has the following additional properties:properties:• the load capacity in tons (type double)the load capacity in tons (type double)• towing capacity in pounds (type int)towing capacity in pounds (type int)

Be sure that you class has a reasonable Be sure that you class has a reasonable complement of constructors, accessor and complement of constructors, accessor and mutator methods, and suitably defined equals mutator methods, and suitably defined equals and toString methods. Write a program to test all and toString methods. Write a program to test all of your methods.of your methods.

Page 13: Object class

Bigger problem – part 1Bigger problem – part 1 The following is some code for a video game. First, there is an Alien class that The following is some code for a video game. First, there is an Alien class that

represents monsters:represents monsters:public class Alien {public class Alien {

public static final int Snake_Alien = 0;public static final int Snake_Alien = 0;public static final int Ogre_Alien = 1;public static final int Ogre_Alien = 1;public static final int Marshmallow_Man_Alien = 2;public static final int Marshmallow_Man_Alien = 2;

public int type;public int type; //stores one of the three above types//stores one of the three above typespublic int health; //0=dead; 100=full strengthpublic int health; //0=dead; 100=full strengthpublic String name;public String name;

public Alien ( int type, int health, String name ) {public Alien ( int type, int health, String name ) {this.type = type;this.type = type;this.health = health;this.health = health;this.name = name;this.name = name;

}}}}

The code is not very object-oriented and does not support information hiding The code is not very object-oriented and does not support information hiding in the Alien class. Rewrite the code so that inheritance is used to represent in the Alien class. Rewrite the code so that inheritance is used to represent the different types of aliens instead of the “type” parameter. This should the different types of aliens instead of the “type” parameter. This should result in deletion of the “type” parameter. Also rewrite the Alien class to hide result in deletion of the “type” parameter. Also rewrite the Alien class to hide the member variables and create a “getDamage” method for each derived the member variables and create a “getDamage” method for each derived class that returns the amount of damage the alien inflicts.class that returns the amount of damage the alien inflicts.

Page 14: Object class

Bigger problem – part 2Bigger problem – part 2 Next we have the AlienPack class that represents a band of aliens and how much Next we have the AlienPack class that represents a band of aliens and how much

damage they can inflict:damage they can inflict:public class AlienPack {public class AlienPack {

private Alien aliens[];private Alien aliens[];public AlienPack ( int numAliens ) {public AlienPack ( int numAliens ) {

aliens = new Alien[ numAliens ];aliens = new Alien[ numAliens ];}}public void addAlien ( Alien newAlien, in index ) {public void addAlien ( Alien newAlien, in index ) {

aliens[index] = newAlien;aliens[index] = newAlien;}}public Alien[] getAliens ( ) {public Alien[] getAliens ( ) {

return aliens;return aliens;}}public int calculateDamage ( ) {public int calculateDamage ( ) {

int damage = 0;int damage = 0;for (int i=0; i<aliens.length; i++) {for (int i=0; i<aliens.length; i++) {

if (aliens[i].type==Alien.Snake_Alien)if (aliens[i].type==Alien.Snake_Alien) damage += damage += 10;10;

else if (aliens[i].type==Alien.Ogre_Alien)else if (aliens[i].type==Alien.Ogre_Alien) damage += 6;damage += 6;else if (aliens[i].type==Alien.Marshmallow_Man_Alien)else if (aliens[i].type==Alien.Marshmallow_Man_Alien) damage += 1;damage += 1;

}}return damage;return damage;

}}}}

Rewrite the calculateDamage method to use getDamage and write a main method that Rewrite the calculateDamage method to use getDamage and write a main method that tests the code.tests the code.