Java Implementation: Part 4 Software Construction Lecture 9.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
Java Software Solutions
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
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.
Chapter 10 Classes Continued
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Java Implementation Software Construction Lecture 6.
Programming Languages and Paradigms Object-Oriented Programming.
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.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Java Implementation: Part 3 Software Construction Lecture 8.
Memory Allocation Recall: we use a reference variable to refer to instances of a class. The value in a reference variable is, essentially, a pointer to.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Classes Dwight Deugo Nesa Matic
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Nested Classes CompSci 230 S Software Construction.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
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.
Advanced Java class Nested Classes & Interfaces. Types of Nested Classes & Interfaces top-level nested –classes –interfaces inner classes –member –local.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Topic: Classes and Objects
Chapter 5: Enhancing Classes
CompSci 230 S Software Construction
Java Primer 1: Types, Classes and Operators
CSC 205 Java Programming II
Java Programming Language
Chapter 8 Classes User-Defined Classes and ADTs
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

Java Implementation: Part 4 Software Construction Lecture 9

Agenda 2 Topics: – Enum Types – Memory allocation: another view of Java’s type system – Object Identity, Assignment, Equality, and Copying The Object class Overriding equals() and toString() Cloning – Nested Classes What and Why Reading, in The Java Tutorials:The Java Tutorials – Enum Types and Nested Classes pages, in the Classes and Objects Lesson. Enum TypesNested ClassesClasses and Objects – Object as a Superclass page, in the Interface and Inheritance Lesson. Object as a SuperclassInterface and Inheritance – Equality, Relational, and Conditional Operators page, in the Language Basics Lesson. Equality, Relational, and Conditional OperatorsLanguage Basics For reference: – The 3 things you should know about hashCode(), Eclipse Source Developer, available 20 March The 3 things you should know about hashCode()

Learning objectives for this week 3 Students will be competent at implementing OO designs in Java – Enums, memory allocation, object identity & assignment & equality & cloning, nested classes The lectures will give you the basic “theory”, but they won’t give you a “working understanding” – you have to do the hard-yards of putting these ideas into practice. – You won’t even understand the theory, if you listen passively to lectures. I’ll try to help you “learn how to learn” from the Java tutorials. – You’ll get many chances to develop your understanding in your lab assignments for this course.

Enum Types 4 “An enum type is a special data type that enables for a variable to be a set of predefined constants. – The variable must be equal to one of the values that have been predefined for it. – Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. “Because they are constants, the names of an enum type's fields are in uppercase letters. “… define an enum type by using the enum keyword. – For example, you would specify a days-of-the-week enum type as: “You should use enum types any time you need to represent a fixed set of constants. – That includes natural enum types such as the planets in our solar system and – data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.” public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Memory Allocation 5 We use a reference variable to refer to instantiated objects. – The value in a reference variable is, essentially, a pointer to an object. A special value (null) indicates that there is no object. The runtime system (the JVM) interprets reference values as an index into a heap – an area of memory that is set aside, by the JVM, for storing instantiated objects. Formally: the range of allowable values for a reference variable is defined by its reference type. This is a static property. – The reference type of o1 is Object. This means it can point to any instance of Object, or to any instance of any subclass of Object. – The new operator allocates sufficient memory on the heap to store all the fields of the object it is instantiating. 0xfe :Ball -class :Class = Ball xPos :int =10 yPos :int = 20 color :Java.awt.Color = RED int i = 20; Ball b1 = new Ball( 10, i, Color.RED ); i :int = 20 b1 :Ball = 0xfe Object o1 = b1; pointsTo o1 :Object = 0xfe pointsTo static type dynamic type

A model of Java’s type system (for reference) 6 Source: Kollman, R. and Gogolla, M., “Capturing Dynamic Program Behaviour with UML Collaboration Diagrams”, Proc. CSMR, 2001.

Variables, revisited 7 “The Java programming language defines the following kinds of variables: … ” [Variables page of the Language Basics Lesson]VariablesLanguage Basics LifetimeInitialisation Class Variables Loading: Created when a class is loaded (usually when the app or applet is loaded); destroyed when a class is reloaded (rare), or when the app/applet terminates. By default. (An explicit initialisation is generally preferred. ) Instance Variables Instantiation: Created when an object is instantiated; destroyed when an object is garbage-collected. By default. (An explicit initialisation is generally preferred. ) Local Variables Invocation: Created when a method (or a brace-delimited block of code, such as a loop body) is entered; destroyed when a method is exited. Must be initialised explicitly! Parameter s Invocation: Created when a method is entered; destroyed when a method is exited. The implicit parameter ( this ) is the target of the invoking message. The values of explicit parameters are defined in the message.

Object Identity 8 If two reference variables have the same value, they are pointing to the same object. – This relationship is called “object identity”. – You can test it with the == operator. 0xfe :Ball -class :Class = Ball xPos :int =10 yPos :int = 20 color :Java.awt.Color = RED b1 :Ball = 0xfe pointsTo Ball b1 = new Ball( 10, 20, Color.RED ); o1 :Object = 0xfe pointsTo Object o1 = b1; true false System.out.println( o1 == b1 ); System.out.println( (String) o1==b1 ); :String = 0xba xba :String -class :Class = String value :char[] = null pointsTo

Equality test: object identity 9 A box that contains 7 items is not identical to any other box that contains 7 items. – But… we would say “3 + 4 equals 7”. If we want to know whether two boxes are equivalent (= have the same value), we might have to open up the boxes and look inside. – The equals() method is implemented as == in Object. – You should override equals(), if you define a subclass in which the “natural definition” for equality differs from the equals() it inherits. System.out.println( (3+4) == 7 ); System.out.println( new Integer(3+4) == new Integer(7) ); true false System.out.println( (new Integer(3+4)).equals(new Integer(7)) ); System.out.println( (new Integer(7)).equals(3+4) ); true System.out.println( (3+4).equals(new Integer(7)) ); System.out.println( ((Integer)(3+4)).equals(new Integer(7)) );true

The hashCode() Method 10 “The Object class, in the java.lang package, sits at the top of the class hierarchy tree. – Every class is a descendant, direct or indirect, of the Object class. – Every class you use or write inherits the instance methods of Object. – You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. “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. – If you override the equals() method, you change the way two objects are equated and Object 's implementation of hashCode() is no longer valid. – Therefore, if you override the equals() method, you must also override the hashCode() method as well.” The hashCode() method returns an int. – Hashcodes are used in HashSet, HashMap, and some other Collection classes which use a hashing algorithm. These classes will give incorrect results, if equal instances in a Collection have different hashcodes. They will have poor performance, if many unequal instances share the same hashcode.

String Equality – be careful… 11 Strings are immutable. – None of the String methods will modify the value of an existing instance; instead, a new String instance is created, and returned. Some strings are “interned” (= accessible by a hash lookup, at runtime). – You may get a reference to an existing String instance when you ask for a new String. Then again, you might not… – Moral: you should use equals(), and not ==, to test Strings for equality. String s3 = new String("Apple"); String s4 = new String("Apple"); System.out.println("s3==s4:" + (s3==s4)); System.out.println("s3.equals(s4):" + s3.equals(s4)); String s1 = "Apple"; String s2 = "Apple"; System.out.println("s1==s2:" + (s1==s2)); System.out.println("s1.equals(s2):" + s1.equals(s2)); True False True

Other Overridable Object Methods 12 Object has two other methods you might want to override – toString() : returns a String representation of the object – clone() : create a copy of an existing object public class Object {... public boolean equals(Object obj) { return (this == obj); } public String toString() { return getClass().getName()... } protected Object clone() throws CloneNotSupportedException {... }

The getClass() method 13 You cannot override getClass(). – Can you see why this isn’t allowed? Point p1 = new Point(10, 20); Class c = p1.getClass (); System.out.println(c.getName()); System.out.println(c.getSuperclass().getName()); Point java.lang.Object public class Object {... // Returns the runtime class of an object public final Class getClass() {... }... }

Cloning 14 The clone() method in the Object class – Throws an exception, if the class of this object does not implement the interface Cloneable – Creates an object of the same type as the original object – Initialises the clone’s instance variables to the same values as the original object's instance variables This is a shallow copy: any objects that are referenced by instance variables will not be cloned. If an object references another object, then you might want to override clone() so that – It always throws an exception (i.e. is uncloneable), or – It clones the other object, and references it from the clone of the original -- so that the clone of the original can be modified or destroyed without affecting the original.

Nested Classes 15 Definition: A class defined inside another class. Motivation: Some classes only make sense in the context of another enclosing class. Examples: – An Enumeration or Iterator object cannot exist by itself. It makes sense only in association with a collection being enumerated/iterated. – A GUI event handler cannot exist by itself. It makes sense only in association with the GUI component for which it handles events. Reference: the Writing an Event Listener Lesson of the Java Tutorials.Writing an Event Listener – Nested classes define, and enforce, a composition relationship between the outer class and its inner classes: public class MyRegularClass {... } class MyInnerClass {... } Outer class Inner class

Nested Classes: Some Details 16 “A nested class is a member of its enclosing class. – Non- static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. – Static nested classes do not have access to other members of the enclosing class. “As a member of [its outer class], a nested class can be declared private, public, protected, or package private. – (Recall that outer classes can only be declared public or package private.)” “ There are two additional types of inner classes. – You can declare an inner class within the body of a method. Such a class is known as a local inner class. – You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. – You will encounter such classes in advanced Java programming.”

Review 17 Topics: – Enum Types – Memory allocation: another view of Java’s type system – Object Identity, Assignment, Equality, and Copying The Object class Overriding equals() and toString() Cloning – Nested Classes What and Why