Java: advanced object-oriented features

Similar documents
C#: advanced object-oriented features

C#: advanced object-oriented features

Java Fundamentals (II)

Assertions, pre/postconditions

Java: introduction to object-oriented features

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

Assertions. Assertions - Example

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

The class Object. Lecture CS1122 Summer 2008

C12a: The Object Superclass and Selected Methods

Chapter Goals. Chapter 7 Designing Classes. Discovering Classes Actors (end in -er, -or) objects do some kinds of work for you: Discovering Classes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Inheritance (Part 5) Odds and ends

CS260 Intro to Java & Android 03.Java Language Basics

JAVA: A Primer. By: Amrita Rajagopal

Inheritance. Transitivity

CSCE3193: Programming Paradigms

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Java and C# in Depth

PIC 20A The Basics of Java

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

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

Java Enum Java, winter semester ,2018 1

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

C#: framework overview and in-the-small features

Java: framework overview and in-the-small features

CSE 331 Software Design & Implementation

CMSC 132: Object-Oriented Programming II

Domain-Driven Design Activity

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Introduction to Programming Using Java (98-388)

CSE 331 Spring 2018 Midterm

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

INHERITANCE. Spring 2019

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Java Object Oriented Design. CSC207 Fall 2014

1 Shyam sir JAVA Notes

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java Programming Course Overview. Duration: 35 hours. Price: $900

Array. Prepared By - Rifat Shahriyar

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Java Persistence API (JPA) Entities

CSE1720 Delegation Concepts (Ch 2)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

JML tool-supported specification for Java Erik Poll Radboud University Nijmegen

C# and Java. C# and Java are both modern object-oriented languages

Absolute C++ Walter Savitch

The Java Modeling Language JML

Packages. Examples of package names: points java.lang com.sun.security drawing.figures

Formale Entwicklung objektorientierter Software

UC Santa Barbara. CS189A - Capstone. Christopher Kruegel Department of Computer Science UC Santa Barbara

Super-Classes and sub-classes

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: reflection

Check out Polymorphism from SVN. Object & Polymorphism

CSE 331 Software Design & Implementation

Expected properties of equality

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

Abstract Classes and Interfaces

Everything is an object. Almost, but all objects are of type Object!

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

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

Introduction to Inheritance

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Chapter 4 Defining Classes I

OOP Design by Contract. Carsten Schuermann Kasper Østerbye IT University Copenhagen

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

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

Classes, interfaces, & documentation. Review of basic building blocks

CSE 331 Midterm Exam Sample Solution 2/18/15

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

Java Programming Training for Experienced Programmers (5 Days)

Universe Type System for Eiffel. Annetta Schaad

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

JAVA BASICS II. Example: FIFO

Java Overview An introduction to the Java Programming Language

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

Another IS-A Relationship

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

System.out.print(); Scanner.nextLine(); String.compareTo();

CSE wi Midterm Exam 2/8/18. Name UW ID #

WA1278 Introduction to Java Using Eclipse

CS 11 java track: lecture 3

Java: exceptions and genericity

Declarations and Access Control SCJP tips

CS 215 Software Design Homework 3 Due: February 28, 11:30 PM

The Java Type System (continued)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

A Practical Approach to Programming With Assertions

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

a correct statement? You need to know what the statement is supposed to do.

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt

Solutions to Quiz 1 (March 14, 2016)

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

Formal Specification and Verification

equals() in the class Object

Transcription:

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

Packages Classes are grouped in packages A hierarchical namespace mechanism Map to file system pathnames one public class per file Influence class visibility Even if a default anonymous package exists, it is customary to define the package explicitly: E.g.: ch.ethz.inf.se.java.mypkg Tip: notice the useful name convention 3

The statements package and import package declares a package Classes from external packages generally need to be imported using import Classes from java.lang are automatically imported * imports (dynamically) all classes in a package, but not in sub-packages package ch.ethz.inf.se.java.mypkg; import java.util.set; // Only the Set class import java.awt.*; import java.awt.event.*; 4

static imports Introduced in Java 5.0 You can use imported static members of a class as if they were defined (also as static members) in the current class import static java.lang.math.*; double r = cos(pi * theta); When to use: for frequent access to static members of another class (avoids duplication or improper inheritance). Issue: where does a method come from? (Traceability) Tip: use sparingly! 5

Core packages in Java 7.0 java.lang (basic language functionalities, fundamental types, automatically imported) java.util (collections and data structures) java.io and java.nio (old/new file operations API. nio improved in Java 7) java.math (multi-precision arithmetic) java.net (networking, sockets, DNS lookup) java.security (cryptography) java.sql (database access: JDBC) java.awt (native GUI components) javax.swing (platform-independent rich GUI components) 6

Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Abstract classes and interfaces

Abstract classes and interfaces A method may or may not have an implementation if it lacks an implementation, it is abstract A class whose implementation is not complete is also called abstract but even a fully implemented class can be declared abstract Interfaces are a form of fully abstract classes they enable a restricted form of multiple inheritance 8

Abstract classes and methods An abstract class cannot be directly instantiated An abstract method cannot be directly executed If a class has an abstract method, the class itself must be abstract An abstract class cannot be final Useful for conceptualization and partial implementations 9

Interfaces Declared using interface instead of class Equivalent to a fully abstract class you don t use the keyword abstract in an interface A way to have some of the benefits of multiple inheritance, with little hassle (e.g., selecting implementations) A class may implement one or more interfaces An interface can extend one or more interfaces 10

Interface use For typing, implementing an interface is essentially equivalent to extending a class: polymorphism applies All interface methods are implicitly abstract and public All interface attributes are implicitly public, static, and final (must be set by initializers once and for all) Useful for design: specify what, not how Tip: use interfaces to have more flexible designs (but attributes are rarely appropriate in interfaces). 11

Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Special classes and features

The String class Sequences of Unicode characters Immutable class: no setters If initialized upon creation as in: String s = Test ; Exists in the string pool in the stack Uses shared memory No duplicates java.lang.stringbuilder class provides mutable strings 13

Object comparison: equals public boolean equals(object obj) { return (this == obj); } The default semantics compares addresses We can provide a different semantics by overriding Implementation should be an equivalence relation Reflexive, symmetric, transitive For any non-null reference variable x it should be: x.equals(null) == false 14

Class Object: hash code public int hashcode() Returns distinct integers for distinct objects. Its specification: required: o1.equals(o2) implies o1.hashcode() == o2.hashcode() as much as possible: o1.equals(o2) iff o1.hashcode() == o2.hashcode() Overriding equals() in descendants does not guarantee to give the right semantics to hashcode() as well. In general, it may be necessary to explicitly override hashcode(), so that equal objects have equal hash codes. 15

Class Object: string representation public String tostring() { } return getclass().getname() + "@" + Integer.toHexString(hashCode()); Tip: all descendants should override this method Tip: the result should be a concise and informative representation 16

Arrays Arrays are objects but with the familiar syntax to access them Operator [ ] to access components The only available attribute is length All components must a have a common type a common ancestor in the inheritance hierarchy Array components are automatically initialized to defaults 17

Array use // declaration int[] iarray; // definition: size given iarray = new int[7]; // declaration with definition Vehicle[] v = new Vehicle[8]; // polymorphic array (Car, Truck --> Vehicle) v[0] = new Car(); v[1] = new Truck(); // using initializers double[] darray = {2.4, 4.5, 3.14, 7.77}; Vehicle[] v1 = {new Car(), new Truck()}; 18

Multidimensional arrays Multidimensional arrays in Java are just arrays of arrays 3-dimensional array, declaration only: int [][][] threedim; Declaration with initialization: // For 0 i < 4: twodim[i] == null int [][] twodim = new int[4][]; // For 0 i < 4: twodim[i] is array {0, 0} int [][] twodim = new int[4][2]; Jagged array: different components have different size: int [][] jagged = {{3, 4, 5}, {6, 7}}; 19

Enumerated types Denote a finite set of values enum TypeName {VALUE_1,..., VALUE_N}; Within the type system, TypeName is a class that extends class Enum and has N distinct static constants TypeName avalue = TypeName.VALUE_2; By default, each VALUE_k is printed as its own name; to have a different representation, override tostring() A variable of enum type can also be null An enum class can have constructors, attributes, and methods, with some restrictions w.r.t. a full-fledged class 20

Enumerated type example enum EventStatus { APPROVED("A"), PENDING("P"), REJECTED("R"); private String shortform; // constructor must be private: not directly callable private EventStatus(String shortform) { this.shortform = shortform; } } public String getshortform(){ } return shortform; 21

Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Assertions and contracts

Contracts Contracts are specification elements embedded in the program text. They use the same syntax as Boolean expressions of the language. Here s an example with Eiffel syntax. class BankAccount balance: INTEGER deposit (amount: INTEGER) require amount > 0 // precondition do balance := balance + amount ensure balance > old balance end // postcondition invariant balance >= 0 end // class invariant 23

Contracts: preconditions The precondition of a method M specifies requirements that every call to M must satisfy. It is the caller s responsibility to ensure that the precondition is satisfied. ba: BankAccount create ba // object creation ba.deposit (120) // valid call: 120 > 0 ba.deposit (-8) // invalid call: -8 < 0 24

Contracts: postconditions The postcondition of a method M specifies conditions that hold whenever an invocation to M terminates. M s body is responsible to ensure that the postcondition is satisfied. ba: BankAccount create ba // object creation // assume balance is 20 ba.deposit (10) // postcondition ok: 30 > 20 ba.deposit (MAX_INTEGER) // postcondition violation if balance silently overflows into the negatives 25

Contracts: class invariants The class invariant of a class C constrains the states that instances of the class can take. The class invariant s semantics is a combination of the semantics of pre- and postcondition: the class invariant must hold upon object creation, right before every qualified call to public members of C, and right after every call terminates. ba: BankAccount create ba // object creation // class invariant must hold // class invariant must hold ba.deposit (10) // class invariant must hold 26

Assertions Java doesn t natively support contracts, but offers assertions: checks that can be executed anywhere in the code: assert boolean-expr [: message ] If evaluates to true, nothing happens If evaluates to false, throw AssertionError and display message Assertion checking is disabled by default Can be enabled at VM level, with different granularities java -ea MyClass (-da to disable) java -esa MyClass (for system classes assertions) java -ea:mypkg... -da:mypkg.subpkg MyClass (... means: do the same for subpackages) Available since Java 1.4 27

Contracts as assertions We can use assertions to render the semantics of contracts: public class BankAccount { int balance = 0; } void deposit(int amount) { int old_balance = balance; assert amount > 0 : Pre violation balance += amount; assert balance > old_balance : Post violation } No explicit support for class invariants Can we render their semantics with assert? 28

JML: Java Modeling Language JML offers full support for contracts, embedded through Javadoc-like annotations public class BankAccount { int balance = 0; /*@ requires amount > 0; @ ensures balance > \old(balance); @*/ void deposit(int amount) { balance += amount; } //@ invariant balance >= 0; } JML is not part of the standard Java platform, and hence requires specific tools to process the annotations Documentation and resources: http://www.jmlspecs.org 29