Uguaglianza equals() e clone(). Fondamenti di Java Uguali o identici?

Slides:



Advertisements
Similar presentations
Uguaglianza equals() e clone(). Fondamenti di Java Uguali o identici?
Advertisements

Uguaglianza equals() e clone(). Fondamenti di Java Uguali o identici?
Ancora sugli Eventi Gestione degli eventi. Modello 1.1.
Clonazione La clonazione... Ovvero: come costruire una copia (probabilmente che ritorni true su equals?)
Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
Layouts and Graphics. component - container - layout Un Container contiene [0 o +] Components Il Layout specifica come i Components sono disposti nel.
Custom Painting Gestione della Grafica customizzata Vedi anche:
Interfacce. Un interface è una collezione di firme di metodi (senza implementazione). Una interfaccia può dichiarare costanti.
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Lecture 5: Interfaces.
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
Identity and Equality Based on material by Michael Ernst, University of Washington.
Public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } public ABC () {} public.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Programo Issues Cora Pérez Ariza ~ DECSAI ~ UGR Granada, January 28 th & 29 th, 2009.
Lilian Blot BUILDING CLASSES Java Programming Spring 2014 TPOP 1.
Effective Java, Chapter 3: Methods Common to All Objects.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Lecture 28: Abstract Classes & Inheritance Announcements & Review Lab 8 Due Thursday Image and color effects with 2D arrays Read: –Chapter 9 Cahoon & Davidson.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
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.
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.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Java Tutorial. Object-Oriented Programming Concepts Object –a representation of some item state  fields/members and should be encapsulated behavior 
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.
Overriding toString()
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
CSC142 NN 1 CSC 142 Overriding methods from the Object class: equals, toString.
1 CSE 331 The Object class; Object equality and the equals method slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
COMP 110 Some notes on inheritance, review
Polymorphism.
Testing, cont., Equality and Identity
null, true, and false are also reserved.
CSE 1030: Implementing Non-Static Features
Implementing Non-Static Features
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
JavaScript Reserved Words
Overriding methods from the Object class: equals, toString
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Clonazione La clonazione... Ovvero: come costruire una copia
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Agenda Types and identifiers Practice Assignment Keywords in Java
Review for Midterm 3.
CS 240 – Advanced Programming Concepts
Chapter 5 Classes.
Presentation transcript:

Uguaglianza equals() e clone()

Fondamenti di Java Uguali o identici?

Class P class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); }

Main di test public class Test { public static void main(String []a){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; System.out.println(p1); P p2=p1; p2.x=3; System.out.println(p1); } class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); }

Main di test public class Test { public static void main(String []a){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; System.out.println(p1); P p2=p1; p2.x=3; System.out.println(p1); } class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); } x=1 ; y=2 x=3 ; y=2 p1 and p2 refer to te same object!

Oggetti diversi public class Test { public static void main(String a[]) {new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; System.out.println(p1); P p2=new P(); p2.x=1; p2.y=2; System.out.println(p2); p1.x=3; System.out.println(p1); System.out.println(p2); } x=1 ; y=2 x=3 ; y=2 x=1 ; y=2

Come testare l'eguaglianza? public class Test { public static void main(String a[]){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; P p2=new P(); p2.x=1; p2.y=2; // come testare l'uguaglianza di p1 e p2? }

Operatore == public class Test { public static void main(String[] a){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; P p2=new P(); p2.x=1; p2.y=2; System.out.println(p1 == p2); } false

Metodo equals() public class Test { public static void main(String[] a){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; P p2=new P(); p2.x=1; p2.y=2; System.out.println(p1.equals(p2)); } false

Metodo equals() The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true). Ma allora a che serve?

equals per la classe P class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); } public boolean equals(P var){ return (x==var.x && y==var.y) } Equals di Object è la base per implementare il vostro equals

equals() e == public class Test { public static void main(String[] a){new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; P p2=new P(); p2.x=1; p2.y=2; System.out.println(p1.equals(p2)); System.out.println(p1 == p2); } true false

Problema 1… public class Test { public static void main(String[] a)}new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; P p2=null; System.out.println(p1.equals(p2)); System.out.println(p1 == p2); } Error!

equals per la classe P, v.2 class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); } public boolean equals(P var){ if(var==null) return false; return (x==var.x && y=var.y) }

Problema 2… Equals deve comparare due Objects! public class Test { public static void main(String[] a)}new Test();} Test() { P p1=new P(); p1.x=1; P1.y=2; Integer p2=new Integer(3); System.out.println(p1.equals(p2)); System.out.println(p1 == p2); } false

equals per la classe P, v.3 class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); } public boolean equals(Object var){ if (!(var instanceof P)) return false; if(var==null) return false; return (x==((P)var).x && y=((P)var).y) }

Problema 3… public class Test { public static void main(String[] a)}new Test();} Test() { P p1=new P(); p1.x=1; p1.y=2; Q p2=new Q(); p2.x=1; p2.y=2; System.out.println(p1.equals(p2)); System.out.println(p1 == p2); } true false Class Q extends P { int z; }

equals per la classe P, v.3b class P { int x; int y; public String toString() { return ("x="+x+" ; y="+y); } public boolean equals(Object var){ if(var==null) return false; if (var.getClass() != this.getClass()) return false; return (x==((P)var).x && y=((P)var).y) }

e ora… public class Test { public static void main(String[] a)}new Test();} Test() { P z1=new P(); p1.x=1; P1.y=2; Q p2=new Q(); p2.x=1; p2.y=2; System.out.println(p1.equals(p2)); System.out.println(p1 == p2); } false Class Q extends P { int z; }

Quale soluzione scegliere? if (o.getClass() != this.getClass()) return false; oppure if (!(var instanceof P)) return false; ? Dipende...

Proprietà richieste ad equals The equals method implements an equivalence relation: It is reflexive: for any reference value x, x.equals(x) should return true. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

Proprietà richieste ad equals Additional properties: It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false.

equals e hashCode Programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode() (the vice versa need not be true)

Implementazione di hashCode public int hashCode() { int hash = 0; /* a typical implementation: for (int i = 0; i < len; i++) { hash = 31* hash + val[i]; } */ hash = x*31+y; return hash; }

A che serve hashCode? chiave1coda1 chiave2coda2 chiave3coda3... O1O6 O2 O4 O3O5 Tabelle associative Dato un oggetto O1 è possibile calcolarne la chiave C1

Sezione: Modificatori Abstract e Controllo di accesso

Modificatori: abstract Classi dichiarate abstract non possono essere istanziate, e devono essere subclassate. Metodi dichiarati abstract devono essere sovrascritti Una class non abstract non può contenere abstract metods

Modificatori: visibilità publicvisibile da tutti (non def.)visibile da tutti nello stesso package protectedvisibile dalle sottoclassi private nascosta da tutti public class ACorrectClass { private String aUsefulString; public String getAUsefulString() { return aUsefulString; // "get" the value } private void setAUsefulString(String s) { //protected void setAUsefulString(String s) { aUsefulString = s; // "set" the value } Uso di metodi di accesso:

Matrice degli accessi Access Levels SpecifierClassPackageSubclassWorld private YNNN no specifierYYNN protected YYYN public YYYY Vedi anche