SlideShare una empresa de Scribd logo
1 de 16
CompSci 230
Software Construction
Java Implementation: Part 3
Version 1.1 of 20 March 2013: corrected contract for hashCode()
Version 1.2 of 20 March 2013: added slide 6
Agenda


Topics:




Enum Types
Memory allocation: another view of Java’s type system
Object Identity, Assignment, Equality, and Copying






Nested Classes







Enum Types and Nested Classes pages, in the Classes and Objects Lesson.
Object as a Superclass page, in the Interface and Inheritance Lesson.
Equality, Relational, and Conditional Operators page, in the Language Basics
Lesson.

For reference:


2

What and Why

Reading, in The Java Tutorials:




The Object class
Overriding equals() and toString()
Cloning

The 3 things you should know about hashCode(), Eclipse Source Developer,
available 20 March 2013.
COMPSCI 230: S7
Enum Types


―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






―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:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

―You should use enum types any time you need to represent a fixed set of
constants.



3

compass directions (values of NORTH, SOUTH, EAST, and WEST) and
the days of the week.

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

COMPSCI 230: S7
int i = 20;
Ball b1 = new Ball( 10, i, Color.RED );

Memory Allocation


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.
Object o1 = b1;

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.
static
 The new operator allocates sufficient memory on the heap to store
dynamic
type
all the fields of the object 0xfe100140 :Ball type
it is instantiating.
o1 :Object =
i :int = 20
-class :Class = Ball
0xfe100140
b1 :Ball = 0xfe100140
xPos :int =10
pointsTo
pointsTo
yPos :int = 20
4
COMPSCI 230: S7
color :Java.awt.Color =

A model of Java’s type system (for reference)

5

Source: Kollman, R. and Gogolla, M., ―Capturing Dynamic Program Behaviour with UML
Collaboration Diagrams‖, Proc. CSMR, 2001.
COMPSCI 230: S7
Variables, revisited


―The Java programming language defines the following kinds of variables: … ‖
[Variables page of the Language Basics Lesson]

Lifetime
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 By default. (An explicit
is instantiated; destroyed when an
initialisation is generally preferred.
object is garbage-collected.
)

Local
Variables

6

Initialisation

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
Object Identity


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.

0xfe100140 :Ball

-class :Class = Ball
xPos :int =10
pointsTo yPos :int = 20
color :Java.awt.Color =
b1 :Ball = 0xfe100140
RED
pointsTo
Ball b1 = new Ball( 10, 20, Color.RED );
Object o1 = b1;

System.out.println( o1 == b1 );
System.out.println( (String) o1==b1 );

o1 :Object =
0xfe100140

true
false

pointsTo
7

:String = 0xba301030

0xba301030 :String
-class :Class = String
value :char[] = null
COMPSCI 230: S7
Equality test: object identity
System.out.println( (3+4) == 7 );
System.out.println( new Integer(3+4) == new Integer(7) );



A box that contains 7 items is not identical to any other box that
contains 7 items.




true
false

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( (new Integer(3+4)).equals(new Integer(7)) );
System.out.println( (new Integer(7)).equals(3+4) );
System.out.println( (3+4).equals(new Integer(7)) );

true
true

System.out.println( ((Integer)(3+4)).equals(new Integer(7)) );

true

8

COMPSCI 230: S7
Object

The hashCode() Method


―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.


9


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
String Equality – be careful…


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…
String s1 = "Apple";
String s2 = "Apple";
System.out.println("s1==s2:" + (s1==s2));
System.out.println("s1.equals(s2):" + s1.equals(s2));
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));

10



True
True

False
True

Moral: you should use equals(), and not ==, to test Strings for equality.

COMPSCI 230: S7
Other Overridable Object Methods


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 {
...
}
}

11

COMPSCI 230: S7
The getClass() method


You cannot override getClass().


Can you see why this isn’t allowed?
public class Object {
...
// Returns the runtime class of an object
public final Class getClass() {
...
}
...
}

Point p1 = new Point(10, 20);
Class c = p1.getClass ();
System.out.println(c.getName());
System.out.println(c.getSuperclass().getName());
12

Point
java.lang.Object
COMPSCI 230: S7
Cloning


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




If an object references another object, then you might want to
override clone() so that



13

This is a shallow copy: any objects that are referenced by instance
variables will not be cloned.

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.
COMPSCI 230: S7
Nested Classes



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.

Nested classes define, and enforce, a composition relationship
between the outer class and its inner classes:
Outer class

public class MyRegularClass {
...
class MyInnerClass {
...
}

}
14

Inner class

COMPSCI 230: S7
Nested Classes: Some Details


―A nested class is a member of its enclosing class.






―As a member of [its outer class], a nested class can be
declared private, public, protected, or package
private.




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.

(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.



15

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.

COMPSCI 230: S7
Review


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




End of Theme A: The OO Programming Paradigm


16

What and Why

We took a top-down approach: use-case analysis  class design
 implementation.
COMPSCI 230: S7

Más contenido relacionado

La actualidad más candente

Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in javaGarik Kalashyan
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# ProgrammingBhushan Mulmule
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part iiSvetlin Nakov
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
DIDUCE: ICSE-2002 presentation
DIDUCE: ICSE-2002 presentationDIDUCE: ICSE-2002 presentation
DIDUCE: ICSE-2002 presentationhangal
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 

La actualidad más candente (20)

Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
C# overview part 2
C# overview part 2C# overview part 2
C# overview part 2
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part ii
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
C# programming
C# programming C# programming
C# programming
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
Java Basics
Java BasicsJava Basics
Java Basics
 
DIDUCE: ICSE-2002 presentation
DIDUCE: ICSE-2002 presentationDIDUCE: ICSE-2002 presentation
DIDUCE: ICSE-2002 presentation
 
Testing for share
Testing for share Testing for share
Testing for share
 

Similar a CompSci 230 Software Construction Java Implementation

25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.pptPiyushAery
 
information on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptinformation on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptssuserf170c4
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objectsSandeep Chawla
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#Umar Farooq
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture ThreeAngelo Corsaro
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsİbrahim Kürce
 

Similar a CompSci 230 Software Construction Java Implementation (20)

25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt
 
information on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptinformation on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.ppt
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Collections
CollectionsCollections
Collections
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objects
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Java14
Java14Java14
Java14
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 

Último

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 

Último (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 

CompSci 230 Software Construction Java Implementation

  • 1. CompSci 230 Software Construction Java Implementation: Part 3 Version 1.1 of 20 March 2013: corrected contract for hashCode() Version 1.2 of 20 March 2013: added slide 6
  • 2. Agenda  Topics:    Enum Types Memory allocation: another view of Java’s type system Object Identity, Assignment, Equality, and Copying     Nested Classes     Enum Types and Nested Classes pages, in the Classes and Objects Lesson. Object as a Superclass page, in the Interface and Inheritance Lesson. Equality, Relational, and Conditional Operators page, in the Language Basics Lesson. For reference:  2 What and Why Reading, in The Java Tutorials:   The Object class Overriding equals() and toString() Cloning The 3 things you should know about hashCode(), Eclipse Source Developer, available 20 March 2013. COMPSCI 230: S7
  • 3. Enum Types  ―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     ―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: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } ―You should use enum types any time you need to represent a fixed set of constants.   3 compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. 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.‖ COMPSCI 230: S7
  • 4. int i = 20; Ball b1 = new Ball( 10, i, Color.RED ); Memory Allocation  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. Object o1 = b1; 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. static  The new operator allocates sufficient memory on the heap to store dynamic type all the fields of the object 0xfe100140 :Ball type it is instantiating. o1 :Object = i :int = 20 -class :Class = Ball 0xfe100140 b1 :Ball = 0xfe100140 xPos :int =10 pointsTo pointsTo yPos :int = 20 4 COMPSCI 230: S7 color :Java.awt.Color = 
  • 5. A model of Java’s type system (for reference) 5 Source: Kollman, R. and Gogolla, M., ―Capturing Dynamic Program Behaviour with UML Collaboration Diagrams‖, Proc. CSMR, 2001. COMPSCI 230: S7
  • 6. Variables, revisited  ―The Java programming language defines the following kinds of variables: … ‖ [Variables page of the Language Basics Lesson] Lifetime 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 By default. (An explicit is instantiated; destroyed when an initialisation is generally preferred. object is garbage-collected. ) Local Variables 6 Initialisation 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
  • 7. Object Identity  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. 0xfe100140 :Ball -class :Class = Ball xPos :int =10 pointsTo yPos :int = 20 color :Java.awt.Color = b1 :Ball = 0xfe100140 RED pointsTo Ball b1 = new Ball( 10, 20, Color.RED ); Object o1 = b1; System.out.println( o1 == b1 ); System.out.println( (String) o1==b1 ); o1 :Object = 0xfe100140 true false pointsTo 7 :String = 0xba301030 0xba301030 :String -class :Class = String value :char[] = null COMPSCI 230: S7
  • 8. Equality test: object identity System.out.println( (3+4) == 7 ); System.out.println( new Integer(3+4) == new Integer(7) );  A box that contains 7 items is not identical to any other box that contains 7 items.   true false 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( (new Integer(3+4)).equals(new Integer(7)) ); System.out.println( (new Integer(7)).equals(3+4) ); System.out.println( (3+4).equals(new Integer(7)) ); true true System.out.println( ((Integer)(3+4)).equals(new Integer(7)) ); true 8 COMPSCI 230: S7
  • 9. Object The hashCode() Method  ―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.  9  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
  • 10. String Equality – be careful…  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… String s1 = "Apple"; String s2 = "Apple"; System.out.println("s1==s2:" + (s1==s2)); System.out.println("s1.equals(s2):" + s1.equals(s2)); 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)); 10  True True False True Moral: you should use equals(), and not ==, to test Strings for equality. COMPSCI 230: S7
  • 11. Other Overridable Object Methods  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 { ... } } 11 COMPSCI 230: S7
  • 12. The getClass() method  You cannot override getClass().  Can you see why this isn’t allowed? public class Object { ... // Returns the runtime class of an object public final Class getClass() { ... } ... } Point p1 = new Point(10, 20); Class c = p1.getClass (); System.out.println(c.getName()); System.out.println(c.getSuperclass().getName()); 12 Point java.lang.Object COMPSCI 230: S7
  • 13. Cloning  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   If an object references another object, then you might want to override clone() so that   13 This is a shallow copy: any objects that are referenced by instance variables will not be cloned. 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. COMPSCI 230: S7
  • 14. Nested Classes   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. Nested classes define, and enforce, a composition relationship between the outer class and its inner classes: Outer class public class MyRegularClass { ... class MyInnerClass { ... } } 14 Inner class COMPSCI 230: S7
  • 15. Nested Classes: Some Details  ―A nested class is a member of its enclosing class.    ―As a member of [its outer class], a nested class can be declared private, public, protected, or package private.   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. (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.   15 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. COMPSCI 230: S7
  • 16. Review  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   End of Theme A: The OO Programming Paradigm  16 What and Why We took a top-down approach: use-case analysis  class design  implementation. COMPSCI 230: S7