Informatik II (D-ITET) Tutorial 6

Similar documents
Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Informatik II Tutorial 6. Subho Shankar Basu

Informatik II (D-ITET) Tutorial 6. TA: Anwar Hithnawi, Distributed Systems Group, ETH Zürich

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

Object-Oriented Programming (Java)

Week 5-1: ADT Design

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

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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

Inheritance and Polymorphism

What is Inheritance?

CS-202 Introduction to Object Oriented Programming

Create a Java project named week10

Software and Programming 1

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CS260 Intro to Java & Android 03.Java Language Basics

Java Object Oriented Design. CSC207 Fall 2014

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Java Fundamentals (II)

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

CIS 110: Introduction to computer programming

Lecture 10. Overriding & Casting About

Classes and Inheritance Extending Classes, Chapter 5.2

Java: introduction to object-oriented features

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Principles of Object Oriented Programming. Lecture 4

Java Magistère BFA

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

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

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

Super-Classes and sub-classes

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

Distributed Systems Recitation 1. Tamim Jabban

Abstract class & Interface

25. Generic Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Example: Count of Points

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

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

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

COE318 Lecture Notes Week 8 (Oct 24, 2011)

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Distributed Systems Recitation 1. Tamim Jabban

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

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

Java Classes, Inheritance, and Interfaces

ITI Introduction to Computing II

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

JAVA MOCK TEST JAVA MOCK TEST II

Inheritance, Polymorphism, and Interfaces

C08: Inheritance and Polymorphism

CH. 2 OBJECT-ORIENTED PROGRAMMING

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

type conversion polymorphism (intro only) Class class

Inheritance and Polymorphism. CS180 Fall 2007

Rules and syntax for inheritance. The boring stuff

Inheritance and Polymorphism

CMSC 341. Nilanjan Banerjee

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

ITI Introduction to Computing II

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Abstract Classes and Interfaces

Introduction to Programming Using Java (98-388)

Programming II (CS300)

Basic Object-Oriented Concepts. 5-Oct-17

CMSC 132: Object-Oriented Programming II. Inheritance

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Lecture 2: Java & Javadoc

1 Shyam sir JAVA Notes

Computer Science II (20073) Week 1: Review and Inheritance

COP 3330 Final Exam Review

Inheritance. Transitivity

Declarations and Access Control SCJP tips

OBJECT ORİENTATİON ENCAPSULATİON

CISC370: Inheritance

Inheritance and Interfaces

CLASS DESIGN. Objectives MODULE 4

Introduction to Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

First IS-A Relationship: Inheritance

Exercise: Singleton 1

Informatik II Tutorial 7. Subho Shankar Basu

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Example: Count of Points

OVERRIDING. 7/11/2015 Budditha Hettige 82

Chapter 5 Object-Oriented Programming

AP CS Unit 6: Inheritance Notes

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

Exam Duration: 2hrs and 30min Software Design

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

Transcription:

Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich

Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase, areverydescriptiveand uppercaseseparated amethodwhichhasaverylongname() Classes with capital letters: class MyClass{ C++ notation: attributes start with m (mvalue, mnext), not the case with temporary and passed parameters (int tmp) Please, comment more! 2

Solution Ex5.Q1, Q2, Q3 - A Simple Linked List Solution Ex5.Q4 List with Stack Eclipse DEMO 3

4

Java Inheritance and Interfaces Outline Person class example Inheritance Type compatibility Polymorphism instanceof Visibility rules Constructor and super() Final methods and class Abstract classes and methods Interfaces Abstract classes vs. interfaces 5

Class Person Person Name Age Address PhoneNumber tostring getname getage getaddress getphonenumber setaddress(newaddress) setphonenumber(newphonenumber) Attributes Accessors Mutators Getter and Setter Methods 6

Class Person - Implementation public class Person { private String name; private int age; private String address; private String phone; public Person(String name, int age, String address, String phone) { this.name = name; this.age = age; this.address = address; this.phone = phone; public String tostring() { return getname() + " is " + getage() + "old and lives in " + getaddress(); public String getname() { return name; public int getage() { return age; public String getaddress() { return address; public String getphonenumber() { return phone;... 7

Class Student Person Name Age Address PhoneNumber tostring() getname() getage() getaddress() getphonenumber() setaddress(newaddress) setphonenumber(newphonenumber) Student Name Age Address PhoneNumber Legi tostring() getname() getage() getaddress() getphonenumber() getlegi() setaddress(newaddress) setphonenumber(newphonenumber) 8

Class Student Student extends an existing concept, the class Person contains a supplementary field: legi with Getter: getlegi() public class Student extends Person { private String legi; public Student(String name, int age, String address, String phone, String legi){ super(name, age, address, phone); this.legi = legi; public String tostring() { return getname() + " is " + getage() + "old, lives in " + getaddress() + " and has legi-nr.: " + getlegi(); public String getlegi() { return legi; 9

Class Student Student defines a constructor calls the basis class constructor through the usage of super public class Student extends Person { private String m_legi; public Student(String name, int age, String address, String phone, String legi){ super(name, age, address, phone); m_legi = legi; public String tostring() { return getname() + " is " + getage() + "old, lives in " + getaddress() + " and has legi-nr.: " + getlegi(); public String getlegi() { return m_legi; 10

Inheritance Student extends Person Student can: Add new fields legi Add new methods getlegi() Override existing methods tostring() Student cannot: Remove fields Remove methods 11

Why inheritance? Better design Code reuse Code «maintenance» Abstraction of the real world 12

Inheritance 13

Upcasting Cat c = new Cat(); System.out.println(c); Mammal m = c; // upcasting System.out.println(m); /* This printed: Cat@a90653 Cat@a90653 */ Cat is still exactly the same Cat after upcasting, it didn't change to a Mammal, it's just being labeled Mammal right now. This is allowed, because Cat is a Mammal. Upcasting is done automatically, no need to do it manually 14

Upcasting Use static cast with upcasting to avoid overhead of dynamic casting 15

Downcasting Downcasting must be done with dynamic cast to check if the object is actually of the derived class type 16

Downcasting Cat c1 = new Cat(); Animal a = c1; //automatic upcasting to Animal Cat c2 = (Cat) a; //manual downcasting back to a Cat Downcasting must be done manually! Why? Multiple child classes 17

Downcasting 18

Static & Dynamic Cast Person Student Employee Person p = new Person(...); Student s = new Student(...); Employee e = new Employee(...); Person ps = s à ok Person pe = e à ok Student sp = p à compilation error Student sps = ps à compilation error Student dsps = (Student) ps à ok (casting from base class to derived class) Employee deps = (Employee) ps à runtime error (ps points to object of class Student) 19

Static & Dynamic Cast Person Student Employee Person p = new Person(...); Student s = new Student(...); Employee e = new Employee(...); p instanceof Person à true p instanceof Student à false s instanceof Person à true s instanceof Student à true 20

The Object class in Java The Object class in Java Is a superclass for all other classes defined in Java's class libraries, as well as for user-defined Java classes. This does not include primitive types (char, int, float, etc.): they are not classes! When a class is defined in Java, the inheritance from the Object class is implicit, therefore: public class MyClass {... is equivalent to: public class MyClass extends Object {... 21

The Object class in Java Object Person Student Employee Quelle: sun.com 22

Visibility Rules private members Private members in the base class are not accessible to the derived class, and also not to anyone else protected members Protected members are visible to methods in a derived class and also methods in classes in the same package, but not to anyone outside public members Everyone 23

Final Methods and Classes A derived class Can accept the base class methods Or can override the base class methods A method declared as final in the base class cannot be overridden by any derived class A final class cannot be extended! E.g. Integer, Character,... 24

Abstract Classes Abstract method Is a method that all derived classes must implement Abstract class A class that has at least one abstract method If a class derived from an abstract class fails to override an abstract method, the compiler will detect an error Eclipse: 'Hint-Bulb' provides help! 25

Interface The interface in Java is the ultimate abstract class. A class can implement many interfaces. A class implements an interface if it provides definitions for all the methods declared in the interface. So, both abstract classes and interface provide a specification of what subclasses must do. But... 26

Abstract Class vs. Interface 27

Abstract Class vs. Interface Abstract class An abstract class can provide complete code, default code, and/or just stubs that have to be overridden Interface An interface cannot provide any code, much less default code May declare methods as protected abstract All methods declared are implicitly public abstract A class may extend only one abstract class A class may implement several interfaces http://java.sun.com/docs/books/tutorial/java/iandi/index.html 28

Example: Interface IStack public interface IStack { int size(); void push(object obj); Object pop(); Object peek(); boolean empty(); public class MyStack implements IStack { private int size; public int size() { return size; public void push(object obj) {...... 29

Example: Abstract Class BaseStack public abstract class BaseStack implements IStack { public abstract int size(); public abstract void push(object obj); public abstract Object pop(); public Object peek() { Object top = pop(); push(top); return top; public boolean empty() { return size() == 0; public class MyStack extends BaseStack { private GenericList first; public Object peek() { return first.value;... 30

HINTS FOR U6 31

Tips for U6 Q1: Classes, Interfaces Q2: Interfaces and Implementation Q3: Polymorphism Q4: Stack (again): Voluntary Exercise Submission 32

Hints A keyword represents an interface Notation for the dependance of the instantiation of the interface. Thermal sensor instantiates the isensor interface Keyword Property Section with attributes (detailed representation) Private client as a specialized Person Section with operations (detailed representation http://de.wikipedia.org/wiki/klassendiagramm 33

Hints Ex6.Q2 Factory Method A factory method builds an object which implements a certain interface, but the inner functionality of the object is hidden. à Programmer 1 implements different lists which implement the IList interface. à Programmer 2 uses lists but doesn t want to know about the functionality. When Programmer 1 writes a new implementation, Programmer2 has to rewrite all lines of new ListA() as new ListB(). à Programmer 1 puts a factory method at disposal and Programmer 2 can always call for example Factory.giveMeNewList() and gets an object from the newest implementation of the IList interface. 34

ScriptS.GE 35

Hints Ex6.Q3 Generic Lists Exercise sheet 5 Elements of the list: Integers int Exercise sheet 6 Elements of the list: generic objects Object Build your own utility class: ListUtils implements IListUtils: manage generic lists Compare with the utility classes in Q1 and Q3 of Exercise Sheet 5 This time the utility class is instantiated (not static) 36

Hints Ex6.Q3 Generic Lists class List { int value; List next; public List(int v, List e){ value = v; next = e; value v next e value v next e 37

Hints Ex6.Q3 Generic Lists class GenericList { Object value; GenericList next; public GenericList(Object v, GenericList e){ value = v; next = e; <<Interface>> Comparable boolean smallerthan(comparable rhs); value v next e value v next e 38

Hints Ex6.Q3 Generic Lists ListUtilsFactory public static IListUtils create() { <<Interface>> IListUtils sort(genericlist list); public static void main(string[ ] args) { IListUtils utils = ListUtilsFactory.create(); GenericList list = null; // add an object to the list Triangle t = new Triangle(2, 3); utils.add(list, t); // add() first checks if list is null ListUtils sort(genericlist list) { 39

Hints Ex6.Q3a and c Generic Lists Methods are not static anymore! Ex5.Q1: tostring, add, size Can be easily passed Ex5.Q3: sort Similar (same idea) Minimal interfacing This way, it can work with generic objects Interface Comparable public interface Comparable { boolean smallerthan(comparable rhs); You can cast as Comparable without checking its type 40

Hints Ex6.Q3b Implement area() method for Rectangle and Triangle Trivial Will be used in your tests for your list! First implement then look for errors in GenericLists J 41

Hints for E6.Q4 : A Stack Again Non-trivial Self-test: Whoever can do it will have no problem during the exam. Promise J Combines the efficiency of arrays to the effortless growth of lists Implements the IStack Interface à Can be used in u6a2.stackfactory.create() 42

Have Fun! 43