MET08-J. Preserve the equality contract when overriding the equals() method

Size: px
Start display at page:

Download "MET08-J. Preserve the equality contract when overriding the equals() method"

Transcription

1 MET08-J. Preserve the equality contract when overriding the equals() method Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals(). Furthermore, this method must follow the general contract for equal s(), as specified by The Java Language Specification (JLS) [ JLS 2015]. An object is characterized both by its identity (location in memory) and by its state (actual data). The == operator compares only the identities of two objects (to check whether the references refer to the same object); the equals() method defined in java.lang.object can be overridden to compare the state as well. When a class defines an equals() method, it implies that the method compares state. When the class lacks a customized equals() method (either locally declared or inherited from a parent class), it uses the default Object.equals() implementation inherited from Object. The default Object.equals() implementation compares only the references and may produce unexpected results. The equals() method applies only to objects, not to primitives. Enumerated types have a fixed set of distinct values that may be compared using == rather than the equals() method. Note that enumerated types provide an equals() implementation that uses == internally; this default cannot be overridden. More generally, subclasses that both inherit an implementation of equals() from a superclass and lack a requirement for additional functionality need not override the equals() method. The general usage contract for equals(), as specified by the JLS, establishes five requirements: 1. It is reflexive: For any reference value x, x.equals(x) must return true. 2. It is symmetric: For any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. 3. 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) m ust return true. 4. 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. 5. For any non-null reference value x, x.equals(null) must return false. Never violate any of these requirements when overriding the equals() method. Noncompliant Code Example (Symmetry) This noncompliant code example defines a CaseInsensitiveString class that includes a String and overrides the equals() method. The CaseInsensitiveString class knows about ordinary strings, but the String class has no knowledge of case-insensitive strings. Consequently, the CaseInsensitiveString.equals() method should not attempt to interoperate with objects of the String class.

2 public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); this.s = s; // This method violates symmetry if (o instanceof CaseInsensitiveString) { return s.equalsignorecase(((caseinsensitivestring)o).s); if (o instanceof String) { return s.equalsignorecase((string)o); // Comply with MET09-J public int hashcode() {/*... */ public static void main(string[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns true System.out.println(s.equals(cis)); // Returns false By operating on String objects, the CaseInsensitiveString.equals() method violates the second contract requirement (symmetry). Because of the asymmetry, given a String object s and a CaseInsensitiveString object cis that differ only in case, cis.equals(s)) ret urns true, while s.equals(cis) returns false. Compliant Solution In this compliant solution, the CaseInsensitiveString.equals() method is simplified to operate only on instances of the CaseInsensitiv estring class, consequently preserving symmetry:

3 public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); this.s = s; return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equalsIgnoreCase(s); public int hashcode() {/*... */ public static void main(string[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns false now System.out.println(s.equals(cis)); // Returns false now Noncompliant Code Example (Transitivity) This noncompliant code example defines an XCard class that extends the Card class. public class Card { private final int number; public Card(int number) { this.number = number; if (!(o instanceof Card)) { Card c = (Card)o; return c.number == number; public int hashcode() {/*... */

4 class XCard extends Card { private String type; public XCard(int number, String type) { super(number); this.type = type; if (!(o instanceof Card)) { // Normal Card, do not compare type if (!(o instanceof XCard)) { return o.equals(this); // It is an XCard, compare type as well XCard xc = (XCard)o; return super.equals(o) && xc.type == type; public int hashcode() {/*... */ public static void main(string[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); System.out.println(p1.equals(p2)); // Returns true System.out.println(p2.equals(p3)); // Returns true System.out.println(p1.equals(p3)); // Returns false // violating transitivity

5 In the noncompliant code example, p1 and p2 compare equal and p2 and p3 compare equal, but p1 and p3 compare unequal, violating the transitivity requirement. The problem is that the Card class has no knowledge of the XCard class and consequently cannot determine that p2 and p3 have different values for the field type. Compliant Solution (Delegation) Unfortunately, in this case it is impossible to extend the Card class by adding a value or field in the subclass while preserving the equals() cont ract. This problem is not specific to the Card class but applies to any class hierarchy that can consider equal instances of distinct subclasses of some superclass. For such cases, use composition rather than inheritance to achieve the desired effect [ Bloch 2008]. This compliant solution adopts this approach by adding a private card field to the XCard class and providing a public viewcard() method. class XCard { private String type; private Card card; // Composition public XCard(int number, String type) { card = new Card(number); this.type = type; public Card viewcard() { return card; if (!(o instanceof XCard)) { XCard cp = (XCard)o; return cp.card.equals(card) && cp.type.equals(type); public int hashcode() {/*... */ public static void main(string[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); XCard p4 = new XCard(1, "type1"); System.out.println(p1.equals(p2)); // Prints false System.out.println(p2.equals(p3)); // Prints false System.out.println(p1.equals(p3)); // Prints false System.out.println(p1.equals(p4)); // Prints true

6 Compliant Solution (Class Comparison) If the Card.equals() method could unilaterally assume that two objects with distinct classes were not equal, it could be used in an inheritance hierarchy while preserving transitivity: public class Card { private final int number; public Card(int number) { this.number = number; if (!(o.getclass() == this.getclass())) { Card c = (Card)o; return c.number == number; public int hashcode() {/*... */ Noncompliant Code Example (Consistency) A uniform resource locator (URL) specifies both the location of a resource and a method to access it. According to the Java API documentation for Class URL [ API 2014]: Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file. Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null. The defined behavior for the equals() method is known to be inconsistent with virtual hosting in HTTP. Virtual hosting allows a web server to host multiple websites on the same computer, sometimes sharing the same IP address. Unfortunately, this technique was unanticipated when the URL class was designed. Consequently, when two completely different URLs resolve to the same IP address, the URL class considers them to be equal. Another risk associated with the equals() method for URL objects is that the logic it uses when connected to the Internet differs from that used when disconnected. When connected to the Internet, the equals() method follows the steps described in the Java API; when disconnected, it performs a string compare on the two URLs. Consequently, the URL.equals() method violates the consistency requirement for equals(). Consider an application that allows an organization's employees to access an external mail service via The application is designed to deny access to other websites by behaving as a makeshift firewall. However, a crafty or malicious user could nevertheless access an illegitimate website if it were hosted on the same computer as the legitimate website and consequently shared the same IP address. Even worse, if the legitimate website were hosted on a server in a commercial pool of servers, an attacker could register multiple websites in the pool (for phishing purposes) until one was registered on the same computer as the legitimate website, consequently defeating the firewall.

7 public class Filter { public static void main(string[] args) throws MalformedURLException { final URL allowed = new URL(" if (!allowed.equals(new URL(args[0]))) { throw new SecurityException("Access Denied"); // Else proceed Compliant Solution (Strings) This compliant solution compares the string representations of two URLs, thereby avoiding the pitfalls of URL.equals() : public class Filter { public static void main(string[] args) throws MalformedURLException { final URL allowed = new URL(" if (!allowed.tostring().equals(new URL(args[0]).toString())) { throw new SecurityException("Access Denied"); // Else proceed This solution still has problems. Two URLs with different string representation can still refer to the same resource. However, the solution fails safely in this case because the equals() contract is preserved, and the system will never allow a malicious URL to be accepted by mistake. Compliant Solution ( URI.equals() ) A Uniform Resource Identifier (URI) contains a string of characters used to identify a resource; this is a more general concept than an URL. The j ava.net.uri class provides string-based equals() and hashcode() methods that satisfy the general contracts for Object.equals() and Object.hashCode() ; they do not invoke hostname resolution and are unaffected by network connectivity. URI also provides methods for normalization and canonicalization that URL lacks. Finally, the URL.toURI() and URI.toURL() methods provide easy conversion between the two classes. Programs should use URIs instead of URLs whenever possible. According to the Java API Class URI documentation [ API 2014]: A URI may be either absolute or relative. A URI string is parsed according to the generic syntax without regard to the scheme, if any, that it specifies. No lookup of the host, if any, is performed, and no scheme-dependent stream handler is constructed. This compliant solution uses a URI object instead of a URL. The filter appropriately blocks the website when presented with any string other than because the comparison fails.

8 public class Filter { public static void main(string[] args) throws MalformedURLException, URISyntaxException { final URI allowed = new URI(" if (!allowed.equals(new URI(args[0]))) { throw new SecurityException("Access Denied"); // Else proceed Additionally, the URI class performs normalization (removing extraneous path segments such as "..") and relativization of paths [ API 2014], [ Dar win 2004]. Noncompliant Code Example ( java.security.key) The method java.lang.object.equals() by default is unable to compare composite objects such as cryptographic keys. Most Key classes lack an equals() implementation that would override Object's default implementation. In such cases, the components of the composite object must be compared individually to ensure correctness. This noncompliant code example compares two keys using the equals() method. The comparison may return false even when the key instances represent the same logical key. private static boolean keysequal(key key1, Key key2) { if (key1.equals(key2)) { return true; Compliant Solution ( java.security.key) This compliant solution uses the equals() method as a first test and then compares the encoded version of the keys to facilitate provider-independent behavior. For example, this code can determine whether a RSAPrivateKey and RSAPrivateCrtKey represent equivalent private keys [ Sun 2006].

9 private static boolean keysequal(key key1, Key key2) { if (key1.equals(key2)) { return true; if (Arrays.equals(key1.getEncoded(), key2.getencoded())) { return true; // More code for different types of keys here. // For example, the following code can check if // an RSAPrivateKey and an RSAPrivateCrtKey are equal: if ((key1 instanceof RSAPrivateKey) && (key2 instanceof RSAPrivateKey)) { if ((((RSAKey)key1).getModulus().equals( ((RSAKey)key2).getModulus())) && (((RSAPrivateKey) key1).getprivateexponent().equals( ((RSAPrivateKey) key2).getprivateexponent()))) { return true; Exceptions MET08-J-EX0: Requirements of this rule may be violated provided that the incompatible types are never compared. There are classes in the Java platform libraries (and elsewhere) that extend an instantiable class by adding a value component. For example, java.sql.timestamp extends java.util.date and adds a nanoseconds field. The equals() implementation for Timestamp violates symmetry and can cause erratic behavior when Timestamp and Date objects are used in the same collection or are otherwise intermixed [ Bloch 2008]. Risk Assessment Violating the general contract when overriding the equals() method can lead to unexpected results. Rule Severity Likelihood Remediation Cost Priority Level MET08-J Low Unlikely Medium P2 L3 Automated Detection Tool Version Checker Description CodeSonar 4.5p1 FB.BAD_PRACTICE.EQ_GETCLASS_AND_CLASS_CONSTANT FB.CORRECTNESS.OVERRIDING_EQUALS_NOT_SYMMETRIC equals method fails for subtypes equals method overrides equals in superclass and may not be symmetric SonarQube Java Plugin 4.11 S2162

10 Related Guidelines MITRE CWE CWE-697, Insufficient Comparison Bibliography [ API 2014] Class URI Class URL (method equals() ) [ Bloch 2008] Item 8, "Obey the General Contract When Overriding equals" [ Darwin 2004] Section 9.2, "Overriding the equals Method" [ Harold 1997] [ Sun 2006] [ Techtalk 2007 ] Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)" Determining If Two Keys Are Equal (JCA Reference Guide) "More Joy of Sets"

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

Methods Common to all Classes

Methods Common to all Classes Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;

More information

Software Engineering Design & Construction

Software Engineering Design & Construction Winter Semester 16/17 Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Liskov Substitution Principle 2 Liskov Substitution Principle

More information

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Equality. Michael Ernst. CSE 331 University of Washington

Equality. Michael Ernst. CSE 331 University of Washington Equality Michael Ernst CSE 331 University of Washington Object equality A simpleidea: Two objects are equal if they have the same value A subtle idea intuition can be misleading: Same object/reference,

More information

MSC07-J. Prevent multiple instantiations of singleton objects

MSC07-J. Prevent multiple instantiations of singleton objects MSC07-J. Prevent multiple instantiations of singleton objects The singleton design pattern's intent is succinctly described by the seminal work of Gamma and colleagues [ Gamma 1995]: Ensure a class only

More information

Equality. Michael Ernst. CSE 331 University of Washington

Equality. Michael Ernst. CSE 331 University of Washington Equality Michael Ernst CSE 331 University of Washington Object equality A simple idea Two objects are equal if they have the same value A subtle idea intuition can be misleading Same object/reference,

More information

equals() in the class Object

equals() in the class Object equals() in the class Object 1 The Object class implements a public equals() method that returns true iff the two objects are the same object. That is: x.equals(y) == true iff x and y are (references to)

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

java.lang.object: Equality

java.lang.object: Equality java.lang.object: Equality Computer Science and Engineering College of Engineering The Ohio State University Lecture 14 Class and Interface Hierarchies extends Object Runable Cloneable implements SmartPerson

More information

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Creating an Immutable Class. Based on slides by Prof. Burton Ma Creating an Immutable Class Based on slides by Prof. Burton Ma 1 Value Type Classes A value type is a class that represents a value Examples of values: name, date, colour, mathematical vector Java examples:

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 32 April 5, 2013 Equality and Hashing When to override: Equality Consider this example public class Point { private final int x; private final int

More information

For this section, we will implement a class with only non-static features, that represents a rectangle

For this section, we will implement a class with only non-static features, that represents a rectangle For this section, we will implement a class with only non-static features, that represents a rectangle 2 As in the last lecture, the class declaration starts by specifying the class name public class Rectangle

More information

Expected properties of equality

Expected properties of equality Object equality CSE 331 Software Design & Implementation Dan Grossman Spring 2015 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins) A simple idea??

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Kevin Zatloukal Summer 2017 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Overview Notions

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2016 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Object equality A

More information

C12a: The Object Superclass and Selected Methods

C12a: The Object Superclass and Selected Methods CISC 3115 TY3 C12a: The Object Superclass and Selected Methods Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/4/2018 CUNY Brooklyn College 1 Outline The Object class and

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017 COMP 250 Lecture 30 inheritance overriding vs overloading Nov. 17, 2017 1 All dogs are animals. All beagles are dogs. relationships between classes 2 All dogs are animals. All beagles are dogs. relationships

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

The Liskov Substitution Principle

The Liskov Substitution Principle Agile Design Principles: The Liskov Substitution Principle Based on Chapter 10 of Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice Hall, 2003 and on Barbara Liskov

More information

Uguaglianza e Identità. (no, non avete sbagliato corso )

Uguaglianza e Identità. (no, non avete sbagliato corso ) 1 Uguaglianza e Identità (no, non avete sbagliato corso ) Fondamenti di Java Che vuol dire "uguaglianza"? Che vuol dire "Identità"? Class P class P { int x; int y; public String tostring() { return ("x="+x+"

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Just before we start Generics Generics are a

More information

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012 Principles of Software Construction: Objects, Design and Concurrency Polymorphism, part 2 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich, and

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 33 Dec. 1, 2010 Equality Consider this example public class Point {! private final int x; // see note about final*! private final int y;! public Point(int

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Object-Oriented Programming, Part 2 of 3 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Object-Oriented Programming, Part 2 of 3 1 / 16

More information

Effective Java. Object Equality. - Case Studies - Angelika Langer. Trainer/Consultant.

Effective Java. Object Equality. - Case Studies - Angelika Langer. Trainer/Consultant. Effective Java Object Equality - Case Studies - Angelika Langer Trainer/Consultant objective study different implementations of equals() identify and evaluate different techniques object equality - case

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 April 23, 2014 Overriding and Equality HW 10 has a HARD deadline Announcements You must submit by midnight, April 30 th Demo your project to your

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Summer Semester 2015 Liskov Substitution Principle External resource: The Liskov

More information

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad Inheritance, type-checking, and method dispatch Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13

More information

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms

More information

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018 CSE 331 Software Design and Implementation Lecture 10 Equality and Hashcode Announcements Leah Perlmutter / Summer 2018 Announcements This coming week is the craziest part of the quarter! Quiz 4 due tomorrow

More information

Elementary Symbol Tables

Elementary Symbol Tables Symbol Table ADT Elementary Symbol Tables Symbol table: key-value pair abstraction.! a value with specified key.! for value given key.! Delete value with given key. DS lookup.! URL with specified IP address.!

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 November 7, 2018 Overriding Methods, Equality, Enums, Iterators Chapters 25 and 26 Announcements HW7: Chat Server Available on Codio / Instructions

More information

Algorithms ROBERT SEDGEWICK KEVIN WAYNE 3.1 SYMBOL TABLES Algorithms F O U R T H E D I T I O N API elementary implementations ordered operations ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu

More information

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 November 8, 2017 Overriding Methods, Equality, Enums Chapter 26 Announcements HW7: Chat Server Available on Codio / InstrucNons on the web site

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Defective Java Code: Turning WTF code into a learning experience

Defective Java Code: Turning WTF code into a learning experience Defective Java Code: Turning WTF code into a learning experience William Pugh, Professor, Univ. of Maryland TS-6589 Examine some defective Java code to become a better developer, and discuss how to turn

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at  Interfaces. Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,

More information

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt Winter Semester 17/18 Liskov Substitution Principle External resource: The Liskov

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

ELEMENTARY SEARCH ALGORITHMS

ELEMENTARY SEARCH ALGORITHMS BBM 202 - ALGORITHMS DEPT. OF COMPUTER ENGINEERING ELEMENTARY SEARCH ALGORITHMS Acknowledgement: The course slides are adapted from the slides prepared by R. Sedgewick and K. Wayne of Princeton University.

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

MIT EECS Michael Ernst Saman Amarasinghe

MIT EECS Michael Ernst Saman Amarasinghe 6.170 Lecture 11 Equality MIT EECS Michael Ernst Saman Amarasinghe 1 bject equality A simple idea we have intuitions about equality: Two objects are equal if they have the same value Two objects are equal

More information

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 31 April 3, 2013 Overriding, Equality, and Casts Announcements HW 09 due Tuesday at midnight More informajon about exam 2 available on Friday Unfinished

More information

Defective Java Code: Turning WTF code into a learning experience

Defective Java Code: Turning WTF code into a learning experience Defective Java Code: Turning WTF code into a learning experience William Pugh, Professor, Univ. of Maryland TS-6589 Examine some defective Java code to become a better developer, and discuss how to turn

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

More about inheritance

More about inheritance Main concepts to be covered More about inheritance Exploring polymorphism method polymorphism static and dynamic type overriding dynamic method lookup protected access 4.1 The inheritance hierarchy Conflicting

More information

Software Development (cs2500)

Software Development (cs2500) Software Development (cs2500) Lecture 31: Abstract Classes and Methods M.R.C. van Dongen January 12, 2011 Contents 1 Outline 1 2 Abstract Classes 1 3 Abstract Methods 3 4 The Object Class 4 4.1 Overriding

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters Overloaded Methods Sending Messages Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Initialization & Cleanup 2 Overloaded Constructors Sending Parameters accessor method 3 4 Sending Parameters

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

Advanced Topics on Classes and Objects

Advanced Topics on Classes and Objects Advanced Topics on Classes and Objects EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Equality (1) Recall that A primitive variable stores a primitive value e.g., double d1 =

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

cs2010: algorithms and data structures

cs2010: algorithms and data structures cs2010: algorithms and data structures Lecture 11: Symbol Table ADT Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin Algorithms ROBERT SEDGEWICK KEVIN WAYNE 3.1 SYMBOL

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Implementing Object Equivalence in Java Using the Template Method Design Pattern Implementing Object Equivalence in Java Using the Template Method Design Pattern Daniel E. Stevenson and Andrew T. Phillips Computer Science Department University of Wisconsin-Eau Claire Eau Claire, WI

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

CIS 110: Introduction to computer programming

CIS 110: Introduction to computer programming CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 24 October 29, 2018 Arrays, Java ASM Chapter 21 and 22 Announcements HW6: Java Programming (Pennstagram) Due TOMORROW at 11:59pm Reminder: please complete

More information

Conversions and Casting

Conversions and Casting Conversions and Casting Taken and modified slightly from the book The Java TM Language Specification, Second Edition. Written by Sun Microsystems. Conversion of one reference type to another is divided

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Charlie Garrod Michael Hilton

Charlie Garrod Michael Hilton Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 1: Designing classes Behavioral subtyping Charlie Garrod Michael Hilton School of Computer Science 1 Administrivia Homework 1 due

More information

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Effective Java Department of Computer Science University of Maryland, College Park Effective Java Textbook Title Effective Java, Second Edition Author Joshua Bloch

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level CSE1720 Click to edit Master Week text 08, styles Lecture 13 Second level Third level Fourth level Fifth level Winter 2014! Thursday, Feb 27, 2014 1 General Info Continuation of Chapter 9 Read Chapter

More information

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher Principles of Software Construction: Objects, Design, and Concurrency Testing and Object Methods in Java Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Homework 1 due Today 11:59 p.m. Everyone

More information

JAVA MOCK TEST JAVA MOCK TEST III

JAVA MOCK TEST JAVA MOCK TEST III http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

Algorithms ROBERT SEDGEWICK KEVIN WAYNE 3.1 SYMBOL TABLES Algorithms F O U R T H E D I T I O N API elementary implementations ordered operations ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu

More information

Introduction to Java.net Package. CGS 3416 Java for Non Majors

Introduction to Java.net Package. CGS 3416 Java for Non Majors Introduction to Java.net Package CGS 3416 Java for Non Majors 1 Package Overview The package java.net contains class and interfaces that provide powerful infrastructure for implementing networking applications.

More information

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

Java: advanced object-oriented features

Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Packages

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Object typing and subtypes

Object typing and subtypes CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10 Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Exercise Session 10 Today s Exercise Session Pattern of the Day Proxy Quizzes 2 Proxy Pattern Structural

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net Equality in.net Gregory Adam 07/12/2008 This article describes how equality works in.net Introduction How is equality implemented in.net? This is a summary of how it works. Object.Equals() Object.Equals()

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

More information