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

Similar documents
Java: introduction to object-oriented features

Java Fundamentals (II)

Introduction to Inheritance

Java: advanced object-oriented features

Encapsulation. Mason Vail Boise State University Computer Science

CS-202 Introduction to Object Oriented Programming

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

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CH. 2 OBJECT-ORIENTED PROGRAMMING

Java Object Oriented Design. CSC207 Fall 2014

CMSC 132: Object-Oriented Programming II

Chapter 5 Object-Oriented Programming

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

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

Chapter 13. Object Oriented Programming

Practice for Chapter 11

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

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance and Polymorphism

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance (P1 2006/2007)

Inheritance -- Introduction

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

CS153: Compilers Lecture 11: Compiling Objects

Intro to Computer Science 2. Inheritance

Designing and Implementing Classes Topic 6

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Lecture 2: Java & Javadoc

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CPS 506 Comparative Programming Languages. Programming Language

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

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

CS112 Lecture: Defining Instantiable Classes

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

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

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

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Inheritance and Polymorphism

C#: advanced object-oriented features

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

STUDENT LESSON A5 Designing and Using Classes

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 4 Defining Classes I

EEE-425 Programming Languages (2013) 1

Concepts of Programming Languages

Declarations and Access Control SCJP tips

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

Lecture 18 CSE11 Fall 2013 Inheritance

C# Programming for Developers Course Labs Contents

A Short Summary of Javali

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

Java Magistère BFA

Class, Variable, Constructor, Object, Method Questions

Object-Oriented Concepts

Imperative Languages!

Principles of Object Oriented Programming. Lecture 4

COMP 250 Fall inheritance Nov. 17, 2017

Object-Oriented Technology. Rick Mercer

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Programming overview

Inheritance and Interfaces

ECE 122. Engineering Problem Solving with Java

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

ECE 122. Engineering Problem Solving with Java

JAVA: A Primer. By: Amrita Rajagopal

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

First IS-A Relationship: Inheritance

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Handout 9 OO Inheritance.

ITI Introduction to Computing II

CLASS DESIGN. Objectives MODULE 4

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Software Design and Analysis for Engineers

Introduction to Programming Using Java (98-388)

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1

CS260 Intro to Java & Android 03.Java Language Basics

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Building custom components IAT351

Rules and syntax for inheritance. The boring stuff

Inheritance (Part 5) Odds and ends

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

Data Abstraction. Hwansoo Han

Inheritance (Outsource: )

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

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

ITI Introduction to Computing II

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

Distributed Systems Recitation 1. Tamim Jabban

Transcription:

Objects and Classes Lecture 10 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017

All labs have been published Descriptions of the four remaining lab assignments ( Laboration 5 8 ) are available on the course website: http://www.cse.chalmers.se/edu/year/2017/course/tda540/ Do not work on them all at once: plan your time wisely Some Java topics used in the labs will be covered during the upcoming classes The TAs will start grading submissions only after each lab s deadline 1 / 44

Object-oriented programming: a minimal history Mid 1960s Ole-Johan Dahl and Kristen Nygaard develop SIMULA 67, the first object-oriented programming language 1970s Alan Kay, Adele Goldberg, and others develop Smalltalk, a popular object-oriented language, and introduce the term objectoriented programming Mid 1980s Bertrand Meyer develops Eiffel, which popularized object technology for the whole software development lifecycle Mid 1980s Bjarne Stroustrup s C++ adds objectorientation to C, making it a widely used programming paradigm Today many programming languages also support some form of object-oriented features 2 / 44

Objects and objects The basic principles of object-oriented programming are inspired by the idea of modeling real objects as data structures in a program running on a computer. 3 / 44

Objects and objects The basic principles of object-oriented programming are inspired by the idea of modeling real objects as data structures in a program running on a computer. teacher: students: Classroom name: "Prof. Smith" Teacher id: 1 Student id: 2 Student id: 3 Student id: 4 Student Array 3 / 44

Objects-oriented programming languages and objects Object-oriented programming provides expressive features to abstract, modularize, and facilitate reuse of complex programs. In practice: abstraction of complex data types inheritance polymorphism dynamic binding/dispatching 4 / 44

Classes An object-oriented program is an organized collection of classes. A class is a module of code that defines data (the state) and operations on those data (abstract data type). a class defines a type class is a static notion: it refers to program text class BankAccount { // user-defined class Integer balance; // data: how much money in the account void deposit(integer amount) { balance = balance + amount; // operation: // add amount to balance 5 / 44

Objects Objects are instances of classes. an object stores values of certain type (object state = value) object is a dynamic notion: objects exist when a program executes CLASS model/mold static type OBJECT instance dynamic value of a type Integer 42 BankAccount balance: 42 6 / 44

Objects and object references Since objects are dynamic entities while classes are static entities, how can we refer to objects in the program text? Variables of reference types (or simply references) provide a means to do so. class BankAccount { Integer balance; // balance is the name of a reference // attached to an object of class Integer // whose state represents an integer value void deposit(integer amount) { balance = balance + amount; // change the state of the object of class Integer // attached to reference balance 7 / 44

The object reference this Every class implicitly has a special reference this, which refers to the current object of the enclosing class. class BankAccount { Integer balance; void setnewbalance(int balance) { this.balance = balance; 8 / 44

The life of an object What we can do with an object obj: initialize: before first using obj, we have to create it read state: in an expression that refers to some components of obj s state (directly or through a method call) modify state: by calling a method on obj dispose: implicit in Java when an object becomes unreachable BankAccount account; account = new BankAccount(); if (account.balance == 0) { // create a new object // expression referring to // balance in account System.out.println("No money available"); account.deposit(1000); // modify balance in account System.out.println("Now you have " + account.balance + " kr."); 9 / 44

What is in a class? The components of a class are called its members: attributes: represent data components methods: represent operations constructors: special methods for initializing objects class BankAccount { // attribute Integer balance; // method void deposit(integer amount) { balance = balance + amount; // constructor BankAccount() { balance = 0; 10 / 44

Visibility of members The visibility of a class member defines where in a program we can refer to that member (read the value of an attribute, or call a method). Visibility modifiers are keywords to define the visibility of a member x: private: x is only visible in the enclosing class default (no keyword): x is visible within the package where the enclosing class is defined protected: x is visible within the same package and in every subclass of the enclosing class public: x is visible everywhere in the program Visibility modifiers cannot be applied to constructors. 11 / 44

Visibility of members: examples package p; package p; class A { private int a; int b; protected void x() { a = 3; public void y() { b = 4; private void z() { a = b; class Z { public static void main(string[] args) { A o = new A(); o.a = 1; // ERROR! o.b = 2; // OK o.x(); // OK o.y(); // OK o.z(); // ERROR! 12 / 44

Visibility of classes The visibility of a class defines where in a program we can refer to and create objects of that class. Visibility modifiers are keywords to define the visibility of a (top level) class C: default (no keyword): C is visible within the package where it is defined public: C is visible everywhere in the program A constructor has the same visibility of its enclosing class. A class is top level when it is not defined inside another class. The opposite is a nested class, which can have any visibility level (like any other class member). This course mainly deals with top-level classes. 13 / 44

Attributes Attributes are also called instance variables or fields. Each attribute represents part of the state of the object of the class where the attribute is declared Attributes are declared within a class s curly braces, outside any method s body They should not be confused with local variables (declared inside method bodies) Attributes are visible (that is accessible) at least within the methods of the class where they are declared When creating an object, attributes are implicitly initialized to default values according to their types Constructors can introduce different initialization values 14 / 44

Attributes: initialization class BankAccount { // money in the account Integer balance = 100; // name of the owner String owner; // year when account // was opened int openyear; BankAccount account; account = new BankAccount(); // initialization of attributes: // account.balance == 100 // account.owner == null // account.openyear == 0 15 / 44

Methods Methods are also called instance methods or member functions. Each method represents an operation that can be executed on objects of the class where the method is declared Two kinds of operations (one method can do both): procedures (commands) modify the object state functions (queries) return information about the object state Methods are declared within a class s curly braces: t0 methodname(t1 a1, t2 a2,...) { /* body/implementation */ may have arguments (use () after method name if no arguments) must have a return type t0 (use void if method returns no value) Methods are visible (that is callable) at least within the methods of the class where they are declared 16 / 44

Method declaration examples class BankAccount { private int balance; // procedure: modify state, no returned value void deposit(int amount) { balance = balance + amount; // function: return value, do not modify state int getbalance() { return balance; // procedure and function (function with side effects) int withdrawandbalance(int amount) { balance = balance - amount; return balance; 17 / 44

Methods good practices: getters and setters 1. Keep attributes private/protected, so that they cannot be modified directly by objects of other classes 2. Provide getter methods to indirectly get the value of attributes 3. Provide setter methods to indirectly set the value of attributes class BankAccount { private int balance; int getbalance() { return balance; void setbalance(int amount) { balance = amount; 18 / 44

Advantages of using getters and setters Decoupling: you can change the internal representation of an object s state, without affecting other classes Encapsulation: the class retains control over how and when its state is changed First version: Second version: class BankAccount { private int balance; class BankAccount { private int checking; private int savings; int getbalance() { return balance; int getbalance() { return checking + savings; void setbalance(int amount) { balance = amount; void withdraw(int amount) { if (checking > amount) checking = checking - amount; 19 / 44

Information hiding Information hiding is the practice of restricting the visibility of attributes, decoupling their private and public representations, and controlling how to modify the state and who can modify it. Information hiding is one way in which object-oriented programs provide abstraction. The publicly visible attributes and methods of a class are the class s public interface or API (Application Programming Interface). Note that Java s keyword interface identifies a specific mechanism to define public interfaces in Java, but the concept of public interface is more general (in fact we have not discussed Java s interface yet). 20 / 44

Clients A piece of code that manipulates objects of a class C is a client of C. Information hiding is a way of decoupling the client s view and the internal representation of a class As long as a class does not change its public interface, clients do not have to worry about changes in the class s internal representation Public interface: Client code: class BankAccount { int getbalance() { /*... */ void withdraw(int amount) { /*... */ BankAccount account; account = new BankAccount(); // we don t have to worry how getbalance // computes the balance from // the internal representation if (account.getbalance() > 100) System.out.println("Can buy lunch!"); 21 / 44

Constructors Constructors are special methods: They must have the same name as the class where they are defined They have no return type (not even void) They are responsible for initializing attributes of the enclosing class (in a way different from the default values) If a class C declares no constructors, new C() gives an object of class C with all attributes initialized to default values (default constructor) A class may have multiple constructors with different arguments A constructor is invoked implicitly when evaluating a new expression 22 / 44

Constructors: examples Notice the usage of this to refer to attributes with the same name as a method s argument. class Account { int balance; String owner; Account() { balance = 100; // client code Account a1 = new Account(); Account(int balance) { this.balance = balance; Account(String owner) { this.owner = owner; Account a2 = new Account(3000); Account a3 = new Account("John Doe"); 23 / 44

Overloading Overloading means declaring several methods in the same class that have the same name but different signatures: their arguments differ in number, type, or both. Calls to overloaded methods pick the right method based on the number and type of actual arguments. class BankAccount { int balance; void deposit(int amount) { balance = balance + amount; void deposit() { deposit(100); void deposit(double amount) { deposit((int) amount); void deposit(string amount) { deposit(double.parsedouble(amount)); 24 / 44

Constants The keyword final specifies that an attribute, argument, or local variable is constant: they cannot be changed after they are initialized final attributes must be explicitly initialized by every constructor (or directly where the attribute is declared) Style tip: constant attribute names normally are in all caps. class Dice { final int SIDES; Dice() { SIDES = 6; Dice(int sides) { SIDES = sides; void setsides(int sides) { SIDES = sides; // Error! 25 / 44

Static members Attributes and methods declared using the keyword static relate to the whole class where they are declared, as opposed to each instance (object) independently from the others. Thus, static members behave very differently from the instance members we have seen in this class so far. class Bank { static double interest = 0.02; static double interest(double amount) { return amount * (1 + interest); if (new Date() == NEW_YEAR) { balance = Bank.interest(balance); 26 / 44

Static members Attributes and methods declared using the keyword static relate to the whole class where they are declared, as opposed to each instance (object) independently from the others. Thus, static members behave very differently from the instance members we have seen in this class so far. a static attribute is a state component shared by every object of the class where it is declared a static method can only reference static members, as well as its local variables and arguments static members are accessed using their class name instead of an object reference; thus, they are accessed without creating objects of their enclosing class 27 / 44

The main method The method main with signature public static void main(string[] args) is a static method that runs first whenever we run a Java program. From main (which does not need any objects to run because it is a static method) all objects in the program are created as the program continues executing. 28 / 44

When to use static members? In object-oriented programming: instance members are the norm static members are used only for special cases Instance members capture the state of and operations on objects: OPERATION INSTANCE create object: Account a = new Account(); modify object state: a.deposit(100); read current object state: if (a.balance() > 100)... Static members capture global operations and state that are available independent of the created objects: ITEM constant: math operation: global state: STATIC double angle = Math.PI/4.0; double cathetus = hypothenuse * Math.cos(angle); double interest = BankAccount.interest; 29 / 44

Static or instance? Rule of thumb to choose whether member m should be static: Does it make sense to call (method) or access (attribute) m independent of specific objects of its class? 1. If the answer is yes, then you probably need a static member; 2. If the answer is no, then you should go with an instance member. In most cases, the answer should be no! 30 / 44

Static or instance: examples class BankAccount { private int balance; public void withdraw(int amount) { balance = balance - amount; public void deposit(int amount) { balance = balance + amount; Both withdraw and deposit modify the state (attribute balance) of the current object: they must be instance methods. 31 / 44

Static or instance: examples class BankAccount { private static final double interest = 0.02; public static double interest() { return interest; public static int percentinterest() { return (int) (interest() * 100); Both interest and percentinterest are independent of specific instances of class BankAccount, as they both depend on constant interest, which is shared by all instances of BankAccount: they must be static methods. 32 / 44

Static or instance: examples public class Car { public static int addinterest(bankaccount account, double interest) { double withinterest = account.balance() * interest; account.deposit((int) withinterest); The operation addinterest is independent of objects of class Car, as it only operates on objects of class account. Therefore, it is technically OK that it is a static method; however, it probably indicates questionable design: addinterest should probably be an instance method of class BankAccount. 33 / 44

Inheritance Inheritance is a mechanism to reuse previously defined classes in the definition of new classes. class C extends B declares a class C that inherits from a class B. all members of B are also implicitly members of C C is a subclass (descendant, heir) of B; conversely, B is a superclass (predecessor, ancestor) of C class Account { int balance; void deposit(int amount) { balance += amount; class FullAccount extends Account { void withdraw(int amount) { deposit(-amount); void close() { balance = 0; 34 / 44

Overriding When creating a class by inheritance, we can also override (that is, redefine) any methods that are inherited from the superclass. a method s signature cannot change when overriding it (except for return types: see covariant redefinition rule) a method s visibility can only increase (e.g. from protected to public) a static method cannot be overridden Inheritance and overriding support flexible code reuse. class Account { int balance; void withdraw(int amount) { balance -= amount; class NoOverdrawnAccount extends Account { // redefinition of withdraw @Override void withdraw(int amount) { if (amount <= balance) balance -= amount; 35 / 44

super: referencing the superclass The keyword super denotes a reference to an instance of the superclass. It is useful to reuse code while overriding. class Account { class NoOverdrawnAccount extends Account { int balance; @Override void withdraw(int amount) void withdraw(int amount) { if (amount <= balance) { balance -= amount; super.withdraw(amount); // call withdraw s implementation // in Account 36 / 44

Shadowing: local variables over attributes It is forbidden to have multiple variables (local variables or attributes) with the same name declared in the same scope (definition block). However, it is possible to have variables with the same name declared in different but overlapping scopes. In this cases one variable implicitly shadows the other (that is only one variable is accessible): a local variable shadows an attribute with the same name use this to access the attribute class BankAccount { int balance; void setbalance(int balance) { // two variables named balance are visible here: // 1. the method argument balance // 2. the class attribute balance // 1. shadows 2. this.balance = balance; 37 / 44

Shadowing: attributes over attributes It is forbidden to have multiple variables (local variables or attributes) with the same name declared in the same scope (definition block). However, it is possible to have variables with the same name declared in different but overlapping scopes. In this cases one variable implicitly shadows the other (that is only one variable is accessible): a subclass attribute shadows a superclass attribute with the same name (note: this is not the same as overriding; suggestion: avoid redefining attributes!) use super to access the attribute in the superclass class Car { class Volvo extends Car { String factoryid = "ZZZ0000"; String factoryid = "VLV0000"; System.out.println(new Car().factoryId); // "ZZZ0000" System.out.println(new Volvo().factoryId); // "VLV0000" 38 / 44

final methods and classes The keyword final can also be used to restrict inheritance: a method marked as final cannot be overridden a class marked as final cannot be inherited from 39 / 44

Inheritance and types Every class C corresponds to a type, which is a set of values and operations on those values. If C is a subclass of another class B, we call the type of C a subtype of the type of B. Informally, the type of C is a more specialized variant of the type of B. More specialized means that everything we can do on objects of class B, we can also do on objects of class C (inheritance); but the latter may also offer more features (new attributes and methods). We say that C and B are related by the is a relation: an object of class C is an object of class B (but not vice versa). class Car { void opendoor() { /*... */ class Convertible extends Car { void opentop() { /*... */ A convertible is a car! 40 / 44

Static or instance: examples public class Car extends Vehicle { String factoryid() { return "Car-" + super.id(); Method factoryid depends on super, which is a reference to an object of the superclass Vehicle: it must be an instance member, otherwise super may not be defined. 41 / 44

Static or instance: examples public class X extends Y { @Override public int z() { return 42; Method z overrides a method with the same signature in the superclass Y of X. Overriding only applies to instance methods, and hence z cannot be static. 42 / 44

The Object class The system class Object is implicitly a superclass of all Java classes: even when we do not use extends, every class implicitly inherits from Object, which provides a number of basic operations. Methods of Object that is useful to override: public boolean equals(object obj) is used to compare objects by value (according to the specific states of your objects) public int hashcode() is used to return a unique integer value for different object values, and should be consistent with equals: o1.equals(o2) if and only if o1.hashcode() == o2.hashcode() class BankAccount { public boolean equals(object other) // if other is not of class BankAccount, this does not work! { return this.balance == other.balance; public int hashcode() { return this.balance; 43 / 44

Checking the dynamic type of references Sometimes it is useful to check the type of a reference within the program. To this end, the expression variable instanceof RefType evaluates to true if and only if variable is attached to an object whose type is RefType or a subtype of RefType. use instanceof sparingly: in most cases checking the type explicitly is not needed (type checking does that when compiling) the one case where it is useful is when overriding equals, which must take an argument of type Object class BankAccount { boolean equals(object other) { if (!(other instanceof BankAccount)) return false; // a different type, so cannot be value-equal else { return this.balance == other.balance; 44 / 44