Programming in the Large II: Objects and Classes (Part 2)

Similar documents
In Java, to create a class named "B" as a subclass of a class named "A", you would write

class Shape { // Color of the shape. (Recall that class Color // is defined in package java.awt. Assume // that this class has been imported.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

5.6.1 The Special Variable this

Programming in the Small II: Control

Chapter 14 Abstract Classes and Interfaces

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

Programming in the Large II: Objects and Classes (Part 1)

Advanced Computer Programming

ITI Introduction to Computing II

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

Exercise: Singleton 1

What is Inheritance?

ITI Introduction to Computing II

Object Oriented Programming. Java-Lecture 11 Polymorphism

CS-202 Introduction to Object Oriented Programming

OBJECT ORİENTATİON ENCAPSULATİON

Advanced Computer Programming

Inheritance and Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

GUI Event Handlers (Part I)

Polymorphism and Interfaces. CGS 3416 Spring 2018

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Java Fundamentals (II)

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

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

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

Inheritance, and Polymorphism.

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Correctness and Robustness

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

Inheritance and Polymorphism

8. Polymorphism and Inheritance

G Programming Languages - Fall 2012

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

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Advanced Computer Programming

CS1150 Principles of Computer Science Objects and Classes

OBJECT ORIENTED PROGRAMMING

Inheritance (continued) Inheritance

Inheritance (Part 5) Odds and ends

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

CS 11 java track: lecture 3

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

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

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

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

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

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

Inheritance, Polymorphism, and Interfaces

Classes and Inheritance Extending Classes, Chapter 5.2

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

More on Inheritance. Interfaces & Abstract Classes

CSE 143 Lecture 20. Circle

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

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

Inheritance -- Introduction

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

2. The object-oriented paradigm

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

INHERITANCE. Spring 2019

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

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

JAVA MOCK TEST JAVA MOCK TEST II

Inheritance (Outsource: )

More On inheritance. What you can do in subclass regarding methods:

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Polymorphism CSCI 201 Principles of Software Development

Making New instances of Classes

index.pdf January 21,

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object Oriented Programming: Based on slides from Skrien Chapter 2

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

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

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

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

Introduction to Object-Oriented Programming

Polymorphism. Agenda

Abstract Classes and Interfaces

ITI Introduction to Computing II

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What are the characteristics of Object Oriented programming language?

ITI Introduction to Computing II

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

Polymorphism Part 1 1

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

Full file at Chapter 2 - Inheritance and Exception Handling

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

CS 251 Intermediate Programming Inheritance

BBM 102 Introduction to Programming II Spring 2017

OVERRIDING. 7/11/2015 Budditha Hettige 82

Java Magistère BFA

Chapter 10 Classes Continued. Fundamentals of Java

Transcription:

Programming in the Large II: Objects and Classes (Part 2) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1

Agenda Inheritance Polymorphism Abstract Classes Special variables this and super Interfaces 2

Inheritance and Polymorphism OOP allows classes to express the similarities among objects that share some, but not all, of their structure and behavior Such similarities can be expressed using inheritance and polymorphism The term inheritance refers to the fact that one class can inherit part or all of its structure and behavior from another class Polymorphism just means that different objects can respond to the same message in different ways 3

Inheritance The class that does the inheriting is said to be a subclass of the class from which it inherits If class B is a subclass of class A, we also say that class A is a superclass of class B A subclass can add to the structure and behavior that it inherits It can also replace or modify inherited behavior 4

Inheritance Diagram In the diagram shown on the right, above, classes B, C, and D are sibling classes Inheritance can also extend over several generations of classes This whole set of classes forms a small class hierarchy 5

Extending Existing Classes The existing class can be extended to make a subclass The syntax for this is public class (subclass-name) extends (existingclass-name) { Example // Changes and additions public class B extends A { 6

Examples: Vehicles Suppose that a program has to deal with motor vehicles, including cars, trucks, and motorcycles. The program could use a class named Vehicle to represent all types of vehicles Since cars, trucks, and motorcycles are types of vehicles, they would be represented by subclasses of the Vehicle class 7

Examples Diagram: Vehicle 8

Vehicle: Superclass The Vehicle class would include Instance variables such as velocity Instance methods such as getvelocity() and setvelocity() These are variables and methods common to all vehicles The three subclasses of Vehicle Car, Truck, and Motorcycle could then be used to hold variables and methods specific to particular types of vehicles 9

Subclasses of Vehicle The Car class might add an instance variable numberofdoors The Truck class might have an instance variable numbeofaxles The Motorcycle class could have a boolean variable hasbasket 10

Class Vehicle public class Vehicle { protected float velocity; public float getvelocity() { return velocity; public void setvelocity(float newvelocity) { velocity = newvelocity; 11

Class Car class Car extends Vehicle { private int numberofdoors; public int getnumberofdoors() { return numberofdoors; public void setnumberofdoors(int newnumdoors) { numberofdoors = newnumdoors; 12

Testing Vehicle public static void main(string[] args) { Car mycar = new Car(); mycar.setvelocity(80); mycar.setnumberofdoors(4); System.out.println("Velocity = " + mycar.getvelocity() + " Number of doors = " + mycar.getnumberofdoors()); 13

Inherited Variables & Methods Suppose that mycar is a variable of type Car that has been declared and initialized with the statement Car mycar = new Car(); Since class Car extends class Vehicle, a car also has all the structure and behavior of a vehicle This means that a variable mycar.velocity exist mycar.setvelocity() and mycar.getvelocity() also exist 14

A Variable and Inheritance Now, in the real world, cars, trucks, and motorcycles are in fact vehicles The same is true in a program. That is, an object of type Car or Truck or Motorcycle is automatically an object of type Vehicle too A variable that can hold a reference to an object of class A can also hold a reference to an object belonging to any subclass of A 15

Which Statements are Legal? 1 Vehicle myvehicle = mycar; 2 Vehicle myvehicle2 = new Car(); 3 Car mycar2 = myvehicle; 4 Car mycar3 = new Vehicle(); 5 Car mycar4 = (Car) myvehicle; 16

Checking Class of an Object The variable myvehicle holds a reference to a Vehicle object that happens to be an instance of the subclass, Car The object remembers that it is in fact a Car, and not just a Vehicle To test whether a given object belongs to a given class, using the instanceof operator. The test: if (myvehicle instanceof Car) Determines whether the object referred to by myvehicle is in fact a car 17

Type Casting mycar = myvehicle; would be illegal because myvehicle could potentially refer to other types of vehicles that are not cars It's like we cannot assign an int value to a variable of type short, because not every int is a short Similarly, it will not allow you to assign a value of type Vehicle to a variable of type Car because not every vehicle is a car As in the case of ints and shorts, the solution here is to use type-casting. mycar = (Car) myvehicle; 18

Examples: Shapes Three classes, Rectangle, Oval, and RoundRect, could be used to represent the three types of shapes These three classes would have a common superclass, Shape, to represent features that all three shapes have in common 19

Class Shape public class Shape { protected String color; public void setcolor(string newcolor) { color = newcolor; public String getcolor() { return color; public void redraw() { 20

Subclasses of Shape class RoundRect extends Shape { void redraw() {... // commands for drawing a rectangle class Oval extends Shape { void redraw() {... // commands for drawing a circle 21

Method redraw If oneshape is a variable of type Shape, it could refer to an object of any of the types, Rectangle, Oval, or RoundRect As a program executes, and the value of oneshape changes, it could even refer to objects of different types at different times Whenever the statement oneshape.redraw(); is executed, the redraw method that is actually called is the one appropriate for the type of object to which oneshape actually refers. 22

Polymorphism It is possible that the very same statement oneshape.redraw(); will call different methods and draw different shapes as it is executed over and over We say that the redraw() method is polymorphic A method is polymorphic if the action performed by the method depends on the actual type of the object to which the method is applied Polymorphism is one of the major distinguishing 23 features of object-oriented programming

Method redraw() in Shape Whenever a Rectangle, Oval, or RoundRect object has to draw itself, it is the redraw() method in the appropriate class that is executed This leaves open the question, What does the redraw() method in the Shape class do? How should it be defined? We should leave it blank! The fact is that the class Shape represents the abstract idea of a shape, and there is no way to draw such a thing 24

Abstract Classes You can have variables of type Shape, but the objects they refer to will always belong to one of the subclasses of Shape We say that Shape is an abstract class An abstract class is one that is not used to construct objects, but only as a basis for making subclasses 25

Abstract vs. Concrete Classes An abstract class exists only to express the common properties of all its subclasses A class that is not abstract is said to be concrete You can create objects belonging to a concrete class, but not to an abstract class. A variable whose type is given by an abstract class can only refer to objects that belong to concrete subclasses of the abstract class. 26

Abstract Method We say that the redraw() method in class Shape is an abstract method since it is never meant to be called The redraw() method in Shape has to be there only to tell the computer that all Shapes understand the redraw message As an abstract method, it exists merely to specify the common interface of all the actual, concrete versions of redraw() in the subclasses of Shape 27

Modifier abstract Shape and its redraw() method are semantically abstract You can also tell the computer, syntactically, that they are abstract by adding the modifier abstract to their definitions For an abstract method, the block of code that gives the implementation of an ordinary method is replaced by a semicolon An implementation must be provided for the abstract method in any concrete subclass of the abstract class 28

Abstract Class Shape public abstract class Shape { protected String color; public void setcolor(string newcolor) { color = newcolor; public String getcolor() { return color; public abstract void redraw(); 29

Abstract Class & Method Is this code legal? Why or why not? class Triangle extends Shape { private float height, width; Is this code legal? Why or why not? public static void main(string[] args) { Shape s = new Shape(); 30

Special Variable this Java provides a special, predefined variable named this that you can use to refer to the object that contains the method This intent of the name, this, is to refer to this object If x is an instance variable in the same object, then this.x can be used as a full name for that variable If othermethod() is an instance method in the same object, then this.othermethod() could be used to call that method 31

Example of Using this public class ThisDemo { private String name; public ThisDemo(String name) { this.name = name; public void methoda() { System.out.println( method A ); public String tostring() { return "name:" + name; public void methodb() { this.methoda(); System.out.println("method B"); System.out.println(this); 32

Example of Using this public static void main(string[] args) { ThisDemo td = new ThisDemo("kku"); td.methodb(); What is the output? 33

The Special Variable super Java also defines another special variable, named super, for use in the definitions of instance methods The variable super is for use in a subclass Like this, super refers to the object that contains the method but it remembers only that it belongs to the superclass of that class It can only be used to refer to methods and variables in the superclass 34

Using super with a Method Let s say that the class that you are writing contains an instance method named dosomething() Consider the subroutine call statement super.dosomething() It tries to execute a method named dosomething() from the superclass If there is none if the dosomething() method was an addition rather than a modification you ll get a syntax error 35

Using super with a Variable The reason super exists is so you can get access to things in the superclass that are hidden in the subclass For example, super.x always refers to an instance variable named x in the superclass The variable in the subclass does not replace the variable of the same name in the superclass; it merely hides it The variable from the superclass can still be accessed, using super. 36

Implementing a Method using super The major use of super is to override a method with a new method that extends the behavior of the inherited method Instead of replacing that behavior entirely The new method can use super to call the method from the superclass Then it can add additional code to provide additional behavior 37

Example: using super (1/3) class Kid { String name; Kid() { name = "a kid"; public void play() { System.out.println(name + " likes to play with toys"); 38

Example: using super (2/3) class SmallKid extends Kid { String name; SmallKid() { name = "a small kid"; SmallKid(String name) {this.name = name; public String tostring() { return this.name + " " + super.name; public void play() { super.play(); System.out.println(name + " likes to play with parents the most"); 39

Example: using super (3/3) public class SuperDemo { public static void main(string[] args) { SmallKid sk = new SmallKid("Ta"); System.out.println(sk); sk.play(); What is the output? 40

Multiple Inheritance Some object-oriented programming languages, such as C++, allow a class to extend two or more superclasses This is called multiple inheritance. 41

Interface Java does have a feature that can be used to accomplish many of the same goals as multiple inheritance: interfaces An interface in this sense consists of a set of instance method interfaces, without any associated implementations A class can implement an interface by providing an implementation for each of the methods specified by the interface 42

Interface Example interface Drawable { public void draw(); interface Fillable { public void fill(); public class Line implements Drawable, Fillable { public void draw() { System.out.println("=== Drawing a line ===="); public void fill() { System.out.println("=== Filling a line ===="); public static void main(string[] args) { Line l = new Line(); l.draw(); l.fill(); 43

References David J. Eck, Introduction to Programming Using Java, Version 5.0, December 2006 http://math.hws.edu/javanotes/ 44