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

Similar documents
Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

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

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

Java Object Oriented Design. CSC207 Fall 2014

Java Magistère BFA

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

Java Fundamentals (II)

CS-202 Introduction to Object Oriented Programming

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

Abstract Classes and Interfaces

What is Inheritance?

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Introduction to Inheritance

Inheritance (Part 5) Odds and ends

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

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

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

Rules and syntax for inheritance. The boring stuff

Chapter 5 Object-Oriented Programming

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

CS 251 Intermediate Programming Inheritance

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

Chapter 5. Inheritance

Inheritance, polymorphism, interfaces

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

ITI Introduction to Computing II

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

Inheritance. Transitivity

C12a: The Object Superclass and Selected Methods

Inheritance and Polymorphism

Inheritance and Interfaces

ITI Introduction to Computing II

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

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

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

CS1150 Principles of Computer Science Objects and Classes

Super-Classes and sub-classes

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

Data Abstraction. Hwansoo Han

COMP 250 Fall inheritance Nov. 17, 2017

Inheritance and Polymorphism

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance (continued) Inheritance

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

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

Java Classes, Inheritance, and Interfaces

What are the characteristics of Object Oriented programming language?

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

More Relationships Between Classes

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

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

C++ Important Questions with Answers

CLASS DESIGN. Objectives MODULE 4

First IS-A Relationship: Inheritance

Inheritance, Polymorphism, and Interfaces

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

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

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Practice for Chapter 11

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

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

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

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CPS 506 Comparative Programming Languages. Programming Language

Programming II (CS300)

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

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

Java: introduction to object-oriented features

Programming Exercise 14: Inheritance and Polymorphism

CS304 Object Oriented Programming Final Term

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

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Lecture 2: Java & Javadoc

Making New instances of Classes

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

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

Object-Oriented Concepts

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

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

JAVA OBJECT-ORIENTED PROGRAMMING

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

INHERITANCE. Spring 2019

PROGRAMMING LANGUAGE 2

EKT472: Object Oriented Programming. Overloading and Overriding Method

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

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

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

Lecture 18 CSE11 Fall 2013 Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

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

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

Distributed Systems Recitation 1. Tamim Jabban

Transcription:

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 hiding inheritance polymorphism abstract classes 2

last time... constructors a constructor is called when an object is created has no return type (not even void) must have the same name as the class are not method we can call another constructor using this() provided it is the first line of the constructor (constructor chaining) this is also a reference to the current object and is used when paramater names are the same as attribute names 3

last time... signatures and overloading A method or constructor signature consists of the name of the method or constructor the input parameters of the method or constructor (number, type and order) Java identifies methods and constructors by their signatures. This allows for method and constructor overloading. overloading allows multiple methods/constructors to have the same name as long as their signatures are different (return types do not matter!) 4

last time... encapsulation / information hiding good oop design makes use of encapsulation (information hiding) hide the internal representation of the state and provide an interface to use the data make all attributes (data) private or protected provide public getters to view data provide public setters to modify data provide other public methods that operate on the data 5

last time... inheritance the extends keyword allows a class to extend or inherit from another class if you don t extend a class you automatically extend Object a class can explicitly extend only one class when you extend a class you receive things (attributes/methods) from the parent class 6

now let s look at more stuff! 7

Java s Object class public class Object{ /* no attributes */ /* single constructor */ public Object(){} } /* 11 methods */ public String tostring(){...} public int hashcode(){...} public boolean equals(object obj){...}... java.lang.object this is Java s root class (its basic non-primitive type) 8

inheritance Let s run the following simple class; public class Student { /* attributes */ public String name; public int id; } public static void main(string[] args){ Student s = new Student(); System.out.println(s); System.out.println(s.toString()); System.out.println(s.hashCode); System.out.println(s.equals(s)); } 9

inheritance Let s run the following simple class; public class Student { /* attributes */ public String name; public int id; } public static void main(string[] args){ Student s = new Student(); System.out.println(s); System.out.println(s.toString()); System.out.println(s.hashCode); System.out.println(s.equals(s)); } Why does this work? 9

inheritance public class Student{ /* attributes */ public String name; public int id;... } when you compile this class it is automatically modified to inherit from the Object class public class Student extends Object{ /* attributes */ public String name; public int id;... } 10

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } Java keyword extends used for inheritance when we inherit from a class we get all public/protected attributes from the parent class we get all public/protected methods from the parent class we get none of the constructors 11

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } Java keyword extends used for inheritance when we inherit from a class we get all public/protected attributes from the parent class we get all public/protected methods from the parent class we get none of the constructors we say that Student is an Object this is the is-a relationship we say that Student has a String this is the has-a relationship this is class composition (not inheritance) 11

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } a class can only have one parent class every class, except Object, has exactly one parent class we get a hierarchy of classes a family tree of classes 12

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } a class can only have one parent class every class, except Object, has exactly one parent class we get a hierarchy of classes a family tree of classes 12

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } we say that Student is a child class of Object Student is a subclass of Object (direct subclass) Student is a derived class of Object Student is a descendent of Object we say that Object is a parent class of Student Object is a super class of Student (direct super class) Object is a ancestor of Student 13

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } a Student object gets everything (state and behaviour) that an Object has in addition to whatever else we define in the Student class this helps us reduce code! 14

inheritance public class Student extends Object{ /* attributes */ public String name; public int id;... } what do we get from Object? tostring() hashcode() equals(object o) eight other methods that we will most likely not use Are these useful? 15

Object s equals method public boolean equals(object obj) checks if both this and obj are the same returns this == obj this is almost certainly not what we want! (why?) Aside: Java s equality operator == should only be used for primitive data types (and null) in most cases. a == b returns true if the value of the left hand side is the same as the value of the right hand side. But for objects, these values are references and not the data itself. 16

Object s tostring method public String tostring() returns a string representation of the object the returned string looks something like Ball@5af660f (for a Ball object) Ljava.lang.String;@462467e5 (for am array of Strings) this is almost certainly not what we want! 17

Object s hashcode method public int hashcode() returns a hash code value for the object can think of this like an integer fingerprint of the object different objects can have the same has code value we may want to use this 18

inheritance and method overriding The methods that we inherit from Object may or may not be useful. We can change the bahaviour of inherited methods though. We do this through method overriding @Override public String tostring(){ return this.name + ", " + this.id; } this will redefine the tostring method in the Student class. all student objects will run this code instead of Object s version this doesn t change Object s code, just the code in a Student Note: the @Override is not part of the Java language. It is an annotation that the compiler to use to make sure that the method you are overriding is actually an inherited method. 19

inheritance and method overriding public class Student extends Object{ /* attributes */ public String name; public int id; } @Override @Override is an annotation public String tostring(){ return this.name + ", " + this.id; } method overriding allows us to redefine a parent s (or grandparent s) method definition. which method is executed? Java first looks in current class if method is not defined, look at parent class if method is not defined, look at parent class... get method from Object 20

inheritance and method overriding rules for method overriding signature must be identical (input parameter names can be different) return type must be the same or more restrictive same if primitive otherwise, same or a subtype (child class) modifiers must be the same or less restrictive protected can be overridden as friendly or public friendly cab be overridden as public we cannot override private methods 21

inheritance and method overriding inheritance lets us reduce write less code by inheriting methods from a parent or grandparent class what happens when we need to make a change to the inherited method (overriding) but most of the code is still the same? we don t want to rewrite the entire method body of the parent. the keyword super is a reference to the parent. we can use it to access parent attributes and parent methods. public class Student extends Object{ } @Override @Override is an annotation public String tostring(){ if( this.name == null ){ return super.tostring(); }else{ return this.name + ", " + this.id; } } 22

inheritance and constructors by default, the first thing that any constructor we write does is call the zero argument constructor of its parent class if want a different parent constructor called we need to explicitly call it using super Take not that super(...) must be called on the first line of the constructor this(...) must be called on the first line of the constructor we cannot call both super() and this() in a constructor we can only access a direct parent s constructor. There is no superduper! 23

inheritance and constructors let s see some examples... 24

inheritance when the "things" that we are modelling in our programs have a natural hierarchical structure, inheritance it lends itself nicely to OOP and inheritance we can have a root class that is very general (animimals) root class has some children that are both animals but also very different from each other we continue creating new classes that become more specific (specific types of dogs) 25

inheritance from Dr. Lanthier s notes http://people.scs.carleton.ca/~lanthier/teaching/comp1406/notes/ COMP1406_Ch4_ClassHierarchiesAndInheritance.pdf 26

inheritance from Dr. Lanthier s notes 27

inheritance banking example 28

inheritance banking example so what? We have reused our code but how does this actually help? 28

polymorphism banking example so what? We have reused our code but how does this actually help? polymorphism to the rescue! 29

polymorphism banking example BankAccount b1 = new PowerSavings(); BankAccount b2 = new BusinessChequing(); BandAccount b3 = new ChequingAccount(); polymorphism allows us to declare a variable for some type (class) and populate it with an object of a different type (class) as long as it is a subclass of the variable type a PowerSavings object is-a BankAccount object, so we are allowed to have a BankAccount variable that references it b1 is a BankAccount object, but the behaviour of it is defined by the PowerSavings class 30

polymorphism polymorphism allows subclasses to define their own unique behaviour without losing the functionality of the superclass(es). A polymorphic object is capable of executing specific behaviour based on its type. Method overloading and overriding are examples of polymorphism. early binding or static binding is when method behaviour of an object is determined at compile time. static, private and final methods are bound at compile time the compiler knows exactly which method is being called late binding or dynamic binding or dynamic dispatch is when method behaviour of an object is determined at runtime the compiler does not know which method is being called so it has to wait until runtime to determine this BankAccount b; is this a BankAccount, a PowerSavings, a BusinessChequing,...? 31

polymorphism with polymorphism objects can act like other objects (very related objects though!) this simplifies code understanding have one array of BankAccount objects that holds everything standardizes method naming all BankAccount objects have similar behaviour defined by the BankAccount class you can add a new kind of BankAccount by simply writing a new class that extends BankAccount and it will still have the same behaviour 32

now let s look at abstract methods and classes 33

abstract methods an abstract method allows us to declare a method without an implementation public abstract String getname(int n); the intention is for subclasses to override (define) the method forces the same method on child classes cannot be a final method (as these cannot be overriden) forces class itself to also be abstract 34

abstract classes an abstract class cannot be instantiated. a concrete class can be instantiated. public abstract class AbstractPlayer{... } the intention is to provide framework for child classes class cannot be instantiated (but is a valid data reference type) cannot be a final class (as these cannot be extended) no restrictions on what can be in an abstract class attributes, methods, constructors does not need to have abstract methods intention is for a descendant class to be concrete 35

abstract classes why use abstract classes? 36

abstract classes why use abstract classes? why use inheritance? 36

abstract classes why use abstract classes? why use inheritance? GameCharacters 36

abstract classes why use abstract classes? why use inheritance? GameCharacters UserCharcater ComputerCharacter 36

abstract classes why use abstract classes? why use inheritance? GameCharacters UserCharcater ComputerCharacter Friend Foe 36

abstract classes why use abstract classes? why use inheritance? abstract GameCharacters UserCharacter ComputerCharacter Friend Foe 36

abstract classes why use abstract classes? why use inheritance? UserCharacter abstract GameCharacters abstract ComputerCharacter Friend Foe 36

abstract classes why use abstract classes? why use inheritance? UserCharacter abstract GameCharacters abstract ComputerCharacter Friend Foe an abstract class can provide an interface or partial interface between implementation and users of code helps modularize code 36

overriding and hiding inheritance can get tricky in Java...(and other languages) method overriding instance methods are overridden same method signature (name and argument list) and return type* method hiding static methods are hidden same method signature (name and argument list) and return type* attribute hiding (field hiding) any attribute in the parent class with the same name is hidden type of attribute does not matter Avoid attribute hiding! method overriding/hiding leads to different behaviour 37

now let s look at Interfaces 38

abstract classes and interfaces Java abstract classes related classes extend the same abstract class similar behaviour is implemented in the abstract class itself different behaviour is implemented in overridden abstract methods you can only extend one single class all classes that extend a given abstract class are related abstract class can provide a contract between code and users of code Java interfaces provide a contract between code and users of code typically specifies how different code interacts with each other a class can implements any number of interfaces classes that implements a given interface can be very unrelated 39

abstract classes and interfaces Java abstract classes often defines what you are usually a noun; Java interfaces often defines what you can do usually an adjective; Comparable, Serielizable, Printable, etc can also define what you are (List, Set) 40

interfaces public interface Printable{ boolean sendtoprinter(string); boolean killprintjob(int); } can contain abstract method declarations (without definition) are public by default (you can omit this) implicitly abstract (you do not write this) can contain constant attributes are public static final by default (can omit this) can have default methods and static methods (these have definitions) and enum types can extend any number of other interfaces is a valid data reference type cannot be instantiated (like an abstract class) we can have variables of this type 41

Comparable consider the Comparable interface public interface Comparable<Type>{ int compareto(type other); // returns an integer X satisfying // X < 0 if this is "less than" other // X = 0 if this is "equal to" other // X > 0 if this is "greater than" other } declared like a class, using interface instead has a single method called compareto() by default all methods are public abstract uses generics (we ll revisit this more later) allows us to treat types as parameters <type> avoids the messiness we saw with Object s equals() 42

Comparable using the Comparable interface public interface Comparable<Type>{ int compareto(type other); } 43

Comparable using the Comparable interface public interface Comparable<Type>{ int compareto(type other); } class that implements the Comparable interface either 43

Comparable using the Comparable interface public interface Comparable<Type>{ int compareto(type other); } class that implements the Comparable interface either must override (define) the method compareto, or 43

Comparable using the Comparable interface public interface Comparable<Type>{ int compareto(type other); } class that implements the Comparable interface either must override (define) the method compareto, or must be abstract 43

Comparable using the Comparable interface public interface Comparable<Type>{ int compareto(type other); } class that implements the Comparable interface either must override (define) the method compareto, or must be abstract public class SomeClass implements Comparable<T>{... public interface SomeInterface extends Comparable<T>{... 43

Comparable public class Student implements Comparable<Student>{ private String name; private int id; } @Override public static int compareto(student other){ if(other == null){ return 1; } return this.getid() - other.getid(); }... Student s = new Student("cat", 12); Student t = new Student("dog", 7); System.out.println( s.compareto(t) ); 44

abstract... abstract methods a method declared without a definition public abstract int foo(string[] in); forces the class to be abstract as well cannot be final abstract classes cannot be instantiated may or may not contain abstract methods are valid reference types and can be subclassed cannot be final concrete classes all methods (declared or inherited) must be defined can be instantiated (all objects other than arrays are instantiations of concrete classes) is a valid data reference type 45

final... final attributes value cannot be changed once it is defined must be defined in constructor or initialization block primitive data types, strings and immutable data types are constants final methods cannot be overridden cannot be abstract final classes cannot be extended cannot be abstract 46

access modifiers... modifier class package subclass world public protected none (default) private everything is accessible from within the class a class in the same package has access to everything except private members a subclass has access to public and protected members everyone else only has access to public members 47