CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.

Slides:



Advertisements
Similar presentations
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Java Implementation: Part 3S CompSci 230 Software Construction.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Interfaces and Inheritance. Interfaces  There are a number of situations in software engineering when it is important for disparate groups of programmers.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism.
Topic 4 Inheritance.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Java Implementation: Part 4 Software Construction Lecture 9.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
The Object class Object package java.lang Object clone equals hashCode toString aCopy toThis hash string ! yesOrNo.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Lecture 12 Inheritance.
03/10/14 Inheritance-2.
CSC 205 Java Programming II
Object-Oriented Programming: Inheritance
Computer Science II Exam 1 Review.
Extending Classes.
Java Programming Language
The Language Package.
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Sampath Kumar S Assistant Professor, SECE
Lecture 25: Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Presentation transcript:

CS2200 Software Development Lecture: Object class A. O’Riordan, 2008

this Revisited this is Java keyword that allows an object to refer to itself or pass its own reference to a method –self-reference used in many OO programming languages—called this in C++, Java, C#; self in Smalltalk and Python For example, in bank account example given previously, a Customer object could have references to two different accounts. We would also like Account objects to have references back to Customer. Java will interpret this as referring to whichever object is using the keyword, and create the appropriate reference For example, to print out a string representation of the object: System.out.println(this)

super if method overrides one of its superclass's methods, you can invoke the overridden method through use of the keyword super, e.g. Superclass and Subclass that overrides printMethod(): public class Superclass: public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } }… public class Subclass extends Superclass { public void printMethod() { //overrides printMethod super.printMethod(); System.out.println("Printed in Subclass"); }… to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown

null What happens when we have created an object reference, but we have not yet assigned an object to it? Java has a special object called null, which should be interpreted as meaning "no object". We can assign null to a reference to make it clear that the reference is not pointing to any object. If you execute x.doSomething() and x is null, you will raise a java.lang.NullPointerException Often used in tests: if ( x != null ) x.doSomething();

Class called Object Object class, defined in the java.lang package, defines and implements behaviour common to all classes—including the ones that you write Classes can be derived directly from Object or derived from classes derived from Object, etc. Every class you use or write inherits the instance methods of Object you may need to override them with code that is specific to your class API:

Methods of Object Object clone() - creates and returns a copy of this object boolean equals(Object obj) - indicates whether some other object is “equal” to this one void finalize() - called by the garbage collector on an object when no more references to the object final Class getClass() - returns the runtime class of an object int hashCode() - returns a hash code value for the object String toString() - returns a string representation of the object The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program

toString() Object's toString() method returns a String representation of the object, which is very useful for debugging/logging The String representation for an object depends entirely on the object, which is why you need to override toString() in your classes, e.g. public class Account { public String toString () { return (accNo + "\t" + name + "\t" + bal)); }… Object’s implementation returns getClass().getName() + + Integer.toHexString(hashCode())

equals() equals() method compares two objects for equality and returns true if they are equal equals() method provided in the Object class uses the identity operator (==)—for primitive data types this is okay For objects, however the equals() method provided by Object tests whether the object references are equal—not objects themselves Therefore need to override equals() Here is an example of a Book class that overrides equals(): public class Book { public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; } …

clone() Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception clone() must be declared as protected Object clone() throws CloneNotSupportedException or public Object clone() throws CloneNotSupportedException The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method

Cloning Arrays if we want to create a copy of an object or an array, we should specify a clone() method, which explicitly creates the new structures public class Bank { private Account[] list; public Account[] cloneAccs(){ Account[] clone = new Account[list.length]; for (int i = 0; i<list.length; i++) clone[i] = list[i]; return clone; }… Note: clones the array, not the objects Note: clones the array, not the objects

Pitfall Common pitfall of using an array of object references is assuming that each reference actually points to an object for (int i = 0; i < list.length; i++) output += list[i].toString() + "\n"; Fails at runtime if one of the cells contains null If it is possible that a reference is null, you must test it: for (int i = 0; i < list.length; i++) if (list[i] != null) output += list[i].toString() + "\n";

instanceof Test the type of a particular object using the instanceof operator if (objectA instanceof ClassB) will yield true if objectA can be upcast to objectB This can save you from a runtime error owing to an improper cast For example: if (obj instanceof MountainBike) MountainBike myBike = (MountainBike)obj; Method overriding preferable for efficiency reasons

getClass() getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name ( getSimpleName() ), its superclass ( getSuperclass() ), and the interfaces it implements ( getInterfaces() ) getClass() has lots of methods (outside scope of this course) – see API For example, the following method gets and displays the class name of an object: void printClassName(Object obj) { System.out.println("The object's class is " obj.getClass().getSimpleName()); } You cannot override getClass()

finalize() and hashcode() Object's implementation of finalize() does nothing—you can override finalize() to do cleanup, such as freeing resources. The finalize() method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. Therefore, you should not rely on this method The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. Note: if you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid