Exercise 13 Self-Study Exercise Sheet

Size: px
Start display at page:

Download "Exercise 13 Self-Study Exercise Sheet"

Transcription

1 Concepts of Object-Oriented Programming AS 2017 Exercise 13 Self-Study Exercise Sheet NOTE: This exercise sheet will not be discussed in an exercise session. We publish it now together with the solution to allow you to better prepare for the final exam. If you have any questions regarding this sheet, please consult your assistant. Subtyping and Behavioral Subtyping Task 1 Consider the class X and its only method foo where ZZZ is placeholder for a class name: class X { /// requires x>0 ( i,j: int 2 i,j x i*j=x) /// ensures result>0 result % 2 = 0 int foo(final int x){ return (new ZZZ()).foo(x); Which of the four classes below could be substituted for ZZZ such that no contracts will be violated? (a) class A { /// requires x 0 /// ensures result = x+1 int foo(final int x) {... (b) class B { /// requires true /// ensures result%2 = 0 int foo(final int x) {... (c) class C { /// requires x%2 = 1 /// ensures result = x+1 int foo(final int x) {... (d) class D { /// requires true /// ensures result = x*(x+1) int foo(final int x) {...

2 Inheritance, Dynamic Method Binding, Multiple Inheritance, and Linearization Task 2 Consider the following Java classes and interfaces: public interface IA { IA g(ia x); public interface IB extends IA { IB g(ia x); IA g(ib x); public interface IC extends IA { IC g(ib x); class B implements IB { public IB g(ia x){system.out.print("b1");return null; public IC g(ib x){system.out.print("b2");return null; class C implements IC { public IC g(ia x){system.out.print("c1");return null; public C g(ib x){system.out.print("c2");return null; class Main{ public static void main(string[] args) { B b = new B(); C c = new C(); IA a1 = b; IA a2 = c; IA r1 = a1.g(a2); IA r2 = a2.g(b); IC r3 = b.g(b); IA r4 = c.g(a2); C r5 = c.g(b); What is the output of the execution of the Main.main method? Explain your answer.

3 Bytecode Verification Task 3 Assume two Java classes A and B and assume that B is a subclass of A. Consider the following byte code: 0: aload_1 1: astore_2 2: goto 0 and assume that the input to the initial node of this code is ([],[A,A,B]), where the first list indicates the contents of the stack and the second list indicates the contents of the registers. After running the bytecode type inference algorithm, what is the inferred input to the initial node? (a) ([],[A,A,A]) (b) ([],[A,A,B]) (c) ([],[A,B,B]) (d) Nothing is inferred the type inference does not terminate (e) Nothing is inferred the type inference rejects the program

4 Parametric Polymorphism Task 4 This is an extended version of a previous exam question. Consider the following Java code: interface Food { interface Grass extends Food { interface Meat extends Food{ abstract class Animal<F extends Food> implements Meat{ abstract void eat(f food); F getlunchbag(){ return lunchbag; ; F lunchbag; final class Sheep extends Animal<Grass>{ void eat(grass f){ final class Wolf extends Animal<Meat> { void eat(meat f){ class Cage { //You are allowed to modify this class Cage(Animal<?> animal){ this.animal = animal; Animal<?> getanimal() { return animal; Animal<?> animal; class Zoo{ void feedanimal(cage cage){ /*code given in each section*/ <F extends Food>void feed(f food, Animal<F> animal){animal.eat(food); void manage(){ /*your code here*/ Clearly a Wolf can eat a Sheep but not the other way around. In the following subtasks we explore if relaxing some of the Java type rules can lead to a situation where a Sheep can eat a Wolf - that is, the method eat is called on an object of the dynamic type Sheep with an argument object of the dynamic type Wolf. All the code you give in the answers to the following sections is in the same package as the code above, and must type check in standard Java. The top method that is called in all sections is Zoo.manage. You can assume that method call arguments are evaluated left to right, and that the program is sequential. You are not allowed to use reflection, raw types, or type-casts. A) Assume the following body of Zoo.feedAnimal(Cage cage), which is rejected by the Java type checker: { feed(cage.getanimal().lunchbag,cage.getanimal()); Make a Sheep eat a Wolf assuming the body of feedanimal is exempted from the type checker. Show all necessary code. You are only allowed to change the Cage class and provide the body of the Zoo.manage method. B) Assume the following body of Zoo.feedAnimal(Cage cage), which is rejected by the Java type checker: {feed(cage.animal.getlunchbag(),cage.animal); Can you make a Sheep eat a Wolf if the body of feedanimal is exempted from the type checker? If so, show all necessary code, otherwise explain why not. You are only allowed to change the Cage class, provide the body of the Zoo.manage method, and add new classes.

5 C) Answer the question in the previous section, assuming the field Cage.animal is final. Explain your answer. Reminder: Java s final fields can be assigned to only in the constructor of the class that declares them. D) Assume the following body of Zoo.feedAnimal(Cage cage), which is rejected by the Java type-checker: {feed(cage.animal.lunchbag,cage.animal); Can you make a Sheep eat a Wolf if the body of feedanimal is exempted from the typechecker? If so, show all necessary code, otherwise explain why not. E) Which of the above cases, that is safe in the sequential case, is unsafe in a multithreaded program? For each such case, explain what can happen in the multithreaded case that cannot in the sequential case. F) The current Java rule for evaluating an expression (including a method call) with wildcard typed arguments is to capture each wildcard in the arguments separately. Propose a more lenient wildcard capture rule than current Java, that is typesafe and accept all the above cases that you deem safe. Hint: define "stable" paths that cannot be modified by calls.

6 Information Hiding and Encapsulation Task 5 Suppose that we have a language with the information hiding rules of Java, but with structural subtyping. What should be the subtyping relations between the following three classes? class A {int foo(); class B {protected int foo(); class C {public int foo(); Task 6 Consider the class Hour, defined as follows: public class Hour { protected int h=0; /// invariant h>=0 && h<24 public void set(int h) { if(h>=0 && h<24) this.h=h; What is the external interface of Hour? Can we extend the code, without changing the class, so that the invariant is broken? If yes, provide an example, and propose how to fix the class.

7 Aliasing, Readonly Types, and Ownership Types Task 7 Consider the following class definitions in the context of the read-only type system taught in the course: class C { public D f; void foo(readonly C other) {... class D { E g; class E { Let a and b be non-null references of type C. Which of the following statements is true: (a) The call a.foo(b) is guaranteed not to change the value of b.f, but may change the value of b.f.g (b) The call a.foo(b) is guaranteed not to change the value of b.f and neither the value of b.f.g (c) The assignment other.f.g = new E(); may appear in the code of foo (d) None of the above is correct Task 8 Consider this code, which uses the topological ownership type system and the owners-asmodifiers discipline. Assume that there is no concurrency and reflection is not used. public class Cell { public int value; public Cell(int value) { this.value = value; public final class Some { public final any Cell a; public final peer Cell b; public final rep Cell c; public Some(any Cell a, peer Cell b, int cval) { this.a = a; this.b = b; this.c = new rep Cell(cval); public void foo(peer Other other) { int av = a.value; int bv = b.value; int cv = c.value; other.bar(this) assert av == a.value assert bv == b.value assert cv == c.value // assertion A // assertion B // assertion C

8 public class Other { public void bar(...) {... public class Client { public void client() {... You will have to choose an implementation for the methods Other.bar and Client.client later in this task. A) After the call other.bar(this), the Some.foo method asserts that the values of the three cells have not been changed by the method call. Without knowing anything about the Other.bar method (except that it type-checks), say, for each of the assertions, if it is guaranteed to hold or if it might fail. You do not have to justify your answers. Provide an implementation for the methods Other.bar and Client.client, such that, when the client method is executed, all assertions which are not guaranteed to hold will fail. B) Does any of your answers in part A change if you are also allowed to add arbitrary methods to class Some? Briefly explain your answer. C) In class Other, write a method clonesome which takes a Some instance and returns a copy of it. As a first priority, the method must maximize the amount of sharing between the original and the cloned object. As a second priority, its parameter type should allow as many clients to call it as possible. You may add additional constructors (but not methods) to class Some.

9 Non-null Types and Initialization Task 9 Consider a Java class Vector, representing a 2 dimensional vector: public class Vector { public Number x; // Remark: Number is a super-interface for public Number y; // Integer, Double, etc. public Vector (Number x, Number y) { this.x = x; this.y = y; Suppose that in some other class we write the following method to calculate the length of the vector represented by a Vector object: public double vectorlength(vector c) { double x = c.x.doublevalue(); double y = c.y.doublevalue(); return Math.sqrt(x * x + y * y); A) This implementation is unsafe - when executed it may throw exceptions. Why? Is this a reasonable behavior? B) Add a pre-condition for the method, specifying what is required to be safe. C) Suppose you are allowed to modify the signature of the method to include non-null type annotations. To what extent can you weaken the necessary pre-condition? D) Suppose that you are also allowed to upgrade the class Vector to include reasonable nonnull type annotations. How does this affect your previous answer? Do these changes to the class seem reasonable? Task 10 Consider the following three classes (declared in the same package): public class Person { Dog? dog; // people might have a dog public Person() { public class Dog { Person! owner; // Dogs must have an owner Bone! bone; // Dogs must have a bone String! breed; // Dogs must have a breed public Dog(Person owner, String breed) { this.owner = owner; this.bone = new Bone(this); this.breed = breed;

10 public class Bone { Dog! dog; // Bones must belong to a dog.. public Bone(Dog toown) { this.dog = toown; A)Annotate the code with non-null and construction type annotations where they are necessary. Explain why the code now type-checks according to construction types. B) Could we provide constructors for classes Dog and Bone with no parameters? C) Now, suppose a (possibly mad) scientist wants to extend the implementations of these classes with some genetic engineering. Firstly, we want to be able to clone a bone. We can add the following method to class Bone to make a copy of an existing bone, and assign it to another Dog: public Bone clone(dog toown) { return new Bone(toOwn); However, our scientist would like to go further, and be able to clone dogs. A cloned Dog should also have its bone cloned along with it, but may be assigned to a new owner: we add the following extra constructor and method to class Dog: Dog(Dog toclone, Person newowner) { this.owner = newowner; this.breed = toclone.breed; this.bone = new Bone(this); public Dog clone(person toown) { return new Dog(this, toown); However, our scientist would like to go still further, and be able to clone people. A cloned Person should also have its dog (if any) cloned along with it: we add the following extra constructor and method to class Person: Person(Person toclone) { Dog? d = toclone.dog; if(d!=null) { this.dog = new Dog(d, this); public Person clone() { return new Person(this); Annotate this extra code with appropriate non-null and construction types annotations. You should guarantee that each of the clone methods (which belong to the public interface) return a committed reference. You should ensure that your answers guarantee that all of the code type-checks - explain your choices. Hint: think carefully about how constructor calls are typed, and what happens if the constructors are called in more than one situation.

11 Reflection Task 11 Which of the following is the defining characteristic of reflection? (a) It allows for much simpler code (b) It enables more flexibility (c) It allows a program to observe and modify its own structure and behavior (d) It is not statically safe (e) It may hurt performance (f) None of the above Task 12 Consider the following Java code: void foo() throws java.lang.exeption { LinkedList<String> xs = new LinkedList<String>(); xs.add("a"); xs.add("b"); xs.add("c"); Class<?> c = xs.getclass(); Method remove = c.getmethod("remove"); xs.add(remove.invoke(xs)); which uses the following methods of class LinkedList<E> public E remove() public boolean add(e e) Which of the following statements is true? The invocation of... (a) c.getmethod("remove") is rejected by the compiler (b) c.getmethod("remove") raises an exception (at run time) (c) remove.invoke(xs) is rejected by the compiler (d) remove.invoke(xs) raises an exception (at run time) (e) xs.add(...) is rejected by the compiler (f) xs.add(...) raises an exception (at run time)

Exercise 13 Self-Study Exercise Sheet

Exercise 13 Self-Study Exercise Sheet Concepts of Object-Oriented Programming AS 2018 Exercise 13 Self-Study Exercise Sheet NOTE: This exercise sheet will not be discussed in an exercise session. We publish it now together with the solution

More information

Exercise 13 Self-Study Exercise Sheet

Exercise 13 Self-Study Exercise Sheet Concepts of Object-Oriented Programming AS 2017 Exercise 13 Self-Study Exercise Sheet NOTE: This exercise sheet will not be discussed in an exercise session. We publish it now together with the to allow

More information

Last name:... First name:... Department (if not D-INFK):...

Last name:... First name:... Department (if not D-INFK):... Concepts of Object-Oriented Programming AS 2016 Concepts of Object-Oriented Programming Midterm Examination 11.11.2016 Prof. Dr. Peter Müller Last name:................................. First name:.................................

More information

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Task 1 In this question, we are in a nominal subtyping setting. Some languages have a special

More information

Exercise 10 Object Structures and Aliasing November 27, 2015

Exercise 10 Object Structures and Aliasing November 27, 2015 Concepts of Object-Oriented Programming AS 2015 Exercise 10 Object Structures and Aliasing November 27, 2015 Task 1 [From a previous exam] In answering this task, do not use reflection, inheritance, and

More information

Exercise 12 Initialization December 16, 2016

Exercise 12 Initialization December 16, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 12 Initialization December 16, 2016 Task 1 Consider a Java class Vector, representing a 2 dimensional vector: public class Vector { public Number!

More information

Exercise 12 Initialization December 15, 2017

Exercise 12 Initialization December 15, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 12 Initialization December 15, 2017 Task 1 Consider a Java class Vector, representing a 2 dimensional vector: public class Vector { public Number!

More information

Exercise 12 Initialization December 15, 2017

Exercise 12 Initialization December 15, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 12 Initialization December 15, 2017 Task 1 Consider a Java class Vector, representing a 2 dimensional vector: public class Vector { public Number!

More information

Last name:... First name:... Department (if not D-INFK):...

Last name:... First name:... Department (if not D-INFK):... Concepts of Object-Oriented Programming AS 2017 Concepts of Object-Oriented Programming Midterm Examination 10.11.2017 Prof. Dr. Peter Müller Last name:................................. First name:.................................

More information

Exercise 12 Initialization December 14, 2018

Exercise 12 Initialization December 14, 2018 Concepts of Object-Oriented Programming AS 2018 Exercise 12 Initialization December 14, 2018 Task 1 Consider a class Vector, representing a 2 dimensional vector, written in a Java-like language with non-null

More information

Exercise 7 Bytecode Verification self-study exercise sheet

Exercise 7 Bytecode Verification self-study exercise sheet Concepts of ObjectOriented Programming AS 2018 Exercise 7 Bytecode Verification selfstudy exercise sheet NOTE: There will not be a regular exercise session on 9th of November, because you will take the

More information

Universe Type System for Eiffel. Annetta Schaad

Universe Type System for Eiffel. Annetta Schaad Universe Type System for Eiffel Annetta Schaad Semester Project Report Software Component Technology Group Department of Computer Science ETH Zurich http://sct.inf.ethz.ch/ SS 2006 Supervised by: Dipl.-Ing.

More information

Exercise 8 Parametric polymorphism November 17, 2017

Exercise 8 Parametric polymorphism November 17, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 8 Parametric polymorphism November 17, 2017 Task 1 Implement a list in Java or C# with two methods: public void add(int i, Object el) public Object

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

Exercise 11 Ownership Types and Non-null Types December 8, 2017

Exercise 11 Ownership Types and Non-null Types December 8, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 11 Ownership Types and Non-null Types December 8, 2017 Task 1 Consider the following method signatures: peer Object foo(any String el); peer Object

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

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

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

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as

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

Conformance. Object-Oriented Programming Spring 2015

Conformance. Object-Oriented Programming Spring 2015 Conformance Object-Oriented Programming 236703 Spring 2015 1 What s Conformance? Overriding: replace method body in sub-class Polymorphism: subclass is usable wherever superclass is usable Dynamic Binding:

More information

Model Solutions. COMP 102: Test May, 2014

Model Solutions. COMP 102: Test May, 2014 Family Name:.............................. Other Names:............................. ID Number:............................... Signature.................................. Model Solutions COMP 102: Test

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017 Task 1 Consider the following Java method: String concatenate(list list) {

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

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

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

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

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

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised

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

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016 Task 1 Consider the following C++ program: class X X(int p) : fx(p)

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

Inheritance and Polymorphism in Java

Inheritance and Polymorphism in Java Inheritance and Polymorphism in Java Introduction In this article from my free Java 8 course, I will be discussing inheritance in Java. Similar to interfaces, inheritance allows a programmer to handle

More information

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017 Task 1 (from a previous exam) Consider the following C++ program: class

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017 Task 1 Consider the following Java method: String concatenate(list list) String

More information

The list abstract data type defined a number of operations that all list-like objects ought to implement:

The list abstract data type defined a number of operations that all list-like objects ought to implement: Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two

More information

Concepts of Object-Oriented Programming Peter Müller

Concepts of Object-Oriented Programming Peter Müller Concepts of Object-Oriented Programming Peter Müller Chair of Programming Methodology Autumn Semester 2017 1.2 Introduction Core Concepts 2 Meeting the Requirements Cooperating Program Parts with Well-Defined

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Generic Universe Types in JML

Generic Universe Types in JML Generic Universe Types in JML Robin Züger Master Project Report Software Component Technology Group Department of Computer Science ETH Zurich http://sct.inf.ethz.ch/ July 2007 Supervised by: Dipl.-Ing.

More information

Concepts of Object-Oriented Programming Peter Müller

Concepts of Object-Oriented Programming Peter Müller Concepts of Object-Oriented Programming Peter Müller Chair of Programming Methodology Autumn Semester 2018 6. Object Structures and Aliasing 2 Object Structures Objects are the building blocks of object-oriented

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

Concepts of Object-Oriented Programming Peter Müller

Concepts of Object-Oriented Programming Peter Müller Concepts of Object-Oriented Programming Peter Müller Chair of Programming Methodology Autumn Semester 2017 1.2 Introduction Core Concepts 2 Meeting the Requirements Cooperating Program Parts with Well-Defined

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

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages! Java Generics II Dr. Hyunyoung Lee!!! 1 Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types

More information

Inheritance and Substitution (Budd chapter 8, 10)

Inheritance and Substitution (Budd chapter 8, 10) Inheritance and Substitution (Budd chapter 8, 10) 1 2 Plan The meaning of inheritance The syntax used to describe inheritance and overriding The idea of substitution of a child class for a parent The various

More information

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Name: CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Directions: Test is closed book, closed notes. Answer every question; write solutions in spaces provided. Use backs of pages for scratch work. Good

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

Inheritance (Part 2) Notes Chapter 6

Inheritance (Part 2) Notes Chapter 6 Inheritance (Part 2) Notes Chapter 6 1 Object Dog extends Object Dog PureBreed extends Dog PureBreed Mix BloodHound Komondor... Komondor extends PureBreed 2 Implementing Inheritance suppose you want to

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information

COE318 Lecture Notes Week 8 (Oct 24, 2011)

COE318 Lecture Notes Week 8 (Oct 24, 2011) COE318 Software Systems Lecture Notes: Week 8 1 of 17 COE318 Lecture Notes Week 8 (Oct 24, 2011) Topics == vs..equals(...): A first look Casting Inheritance, interfaces, etc Introduction to Juni (unit

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

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id): CIS 120 Midterm II November 8, 2013 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing

More information

Java 5 New Language Features

Java 5 New Language Features Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

JAVA OBJECT-ORIENTED PROGRAMMING

JAVA OBJECT-ORIENTED PROGRAMMING SE2205B - DATA STRUCTURES AND ALGORITHMS JAVA OBJECT-ORIENTED PROGRAMMING Kevin Brightwell Thursday January 12th, 2017 Acknowledgements:Dr. Quazi Rahman 1 / 36 LECTURE OUTLINE Composition Inheritance The

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018

Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018 1 Terminology 1 2 Class Hierarchy Diagrams 2 2.1 An Example: Animals...................................

More information

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

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

More information

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

(a) Write the signature (visibility, name, parameters, types) of the method(s) required 1. (6 pts) Is the final comprehensive? 1 2. (6 pts) Java has interfaces Comparable and Comparator. As discussed in class, what is the main advantage of Comparator? 3. (6 pts) We can use a comparator in

More information

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

EXAMINATIONS 2012 END-OF-YEAR SWEN222. Software Design. Question Topic Marks 1. Design Quality Design Patterns Design by Contract 12

EXAMINATIONS 2012 END-OF-YEAR SWEN222. Software Design. Question Topic Marks 1. Design Quality Design Patterns Design by Contract 12 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:..................... EXAMINATIONS 2012 END-OF-YEAR SWEN222 Software Design Time

More information

Cover Page. The handle holds various files of this Leiden University dissertation

Cover Page. The handle   holds various files of this Leiden University dissertation Cover Page The handle http://hdl.handle.net/1887/22891 holds various files of this Leiden University dissertation Author: Gouw, Stijn de Title: Combining monitoring with run-time assertion checking Issue

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

CIS 120 Final Exam 15 December 2017

CIS 120 Final Exam 15 December 2017 CIS 120 Final Exam 15 December 2017 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6] 1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

More information

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer STUDENT NAME: ID: The exam consists of five questions. There are a total of 10 points. You may use the back

More information

A Deep Dive into the Void

A Deep Dive into the Void A Deep Dive into the Void Java ready Advanced null Type Annotations Stephan Herrmann GK Software Stephan Herrmann: A Deep Dive into the Void - EclipseCon Europe 2014 # 2 An Old Problem 1965 Tony Hoare

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

Inheritance & Polymorphism

Inheritance & Polymorphism Inheritance & Polymorphism Procedural vs. object oriented Designing for Inheritance Test your Design Inheritance syntax **Practical ** Polymorphism Overloading methods Our First Example There will be shapes

More information

Polymorphic (Generic) Programming in Java

Polymorphic (Generic) Programming in Java Polymorphic (Generic) Programming in Java We have used the fact that Java classes are arranged as a tree with the built in class Object at the root to write generic or polymorphic code such as the following

More information

Advances in Programming Languages

Advances in Programming Languages O T Y H Advances in Programming Languages APL8: ESC/Java2 David Aspinall (including slides by Ian Stark and material adapted from ESC/Java2 tutorial by David Cok, Joe Kiniry and Erik Poll) School of Informatics

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

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

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

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

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

C++ Inheritance and Encapsulation

C++ Inheritance and Encapsulation C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING FINAL ASSESSMENT FOR Semester 1 AY2017/2018 CS2030 Programming Methodology II November 2017 Time Allowed 2 Hours INSTRUCTIONS TO CANDIDATES 1. This

More information

6. Parametric Types and Virtual Types

6. Parametric Types and Virtual Types 6. Parametric Types and Virtual Types For many programming scenarios, subtype polymorphism is not the best choice. Often more precise type systems are desirable: Types with parameters Specialization of

More information

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

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

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

COMP 401 Spring 2013 Midterm 2

COMP 401 Spring 2013 Midterm 2 COMP 401 Spring 2013 Midterm 2 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overriding עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap A method in a child class overrides a method in the parent class if it has the same name and type signature: Parent void method(int,float)

More information

CSE331 Winter 2014, Midterm Examination February 12, 2014

CSE331 Winter 2014, Midterm Examination February 12, 2014 CSE331 Winter 2014, Midterm Examination February 12, 2014 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 11:20. There are 100 points

More information

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 331 Final Exam 3/16/15 Sample Solution Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information