Example: Count of Points

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

Example: Count of Points

First IS-A Relationship: Inheritance

Instance Members and Static Members

More Relationships Between Classes

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

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

Exercise: Singleton 1

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

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

Subtype Polymorphism

Example: Fibonacci Numbers

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

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Recursion 1. Recursion is the process of defining something in terms of itself.

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

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

What is Inheritance?

Inheritance, Polymorphism, and Interfaces

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Inheritance and Polymorphism

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

Java Fundamentals (II)

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

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

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

Implements vs. Extends When Defining a Class

CH. 2 OBJECT-ORIENTED PROGRAMMING

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

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

CS-202 Introduction to Object Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Practice for Chapter 11

OBJECT ORİENTATİON ENCAPSULATİON

Inheritance. Transitivity

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

INSTRUCTIONS TO CANDIDATES

Inheritance -- Introduction

Programming Languages and Techniques (CIS120)

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

1 Shyam sir JAVA Notes

Exercise. Zheng-Liang Lu Java Programming 273 / 324

Java Object Oriented Design. CSC207 Fall 2014

What are the characteristics of Object Oriented programming language?

25. Generic Programming

Inheritance, polymorphism, interfaces

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

Rules and syntax for inheritance. The boring stuff

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

CMSC 132: Object-Oriented Programming II

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

Class, Variable, Constructor, Object, Method Questions

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

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

VIRTUAL FUNCTIONS Chapter 10

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

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

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

Inheritance (Outsource: )

Object Orientated Programming Details COMP360

Inheritance and Polymorphism

Inheritance and Polymorphism. CS180 Fall 2007

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

CS 251 Intermediate Programming Inheritance

QUESTIONS FOR AVERAGE BLOOMERS

COP 3330 Final Exam Review

Chapter 5. Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Inheritance and Polymorphism

Polymorphism. Agenda

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

Operators and Expressions

Inheritance & Polymorphism

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

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

CS Programming I: Inheritance

Inheritance (continued) Inheritance

CS111: PROGRAMMING LANGUAGE II

type conversion polymorphism (intro only) Class class

C++ Important Questions with Answers

Strict Inheritance. Object-Oriented Programming Winter

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

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

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

index.pdf January 21,

PROGRAMMING LANGUAGE 2

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

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Binghamton University. CS-140 Fall Dynamic Types

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Object Oriented Java

CLASS DESIGN. Objectives MODULE 4

Polymorphism and Inheritance

Transcription:

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; should be placed in the first line in the constructor 11 this.x = x; 12 this.y = y; 13 } 14... 15 } Zheng-Liang Lu Java Programming 241 / 266

Exercise: Singleton In some situations, you may create the only instance of the class. 1 class Singleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static Singleton INSTANCE = new Singleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private Singleton() {} 8 9 // Only way to obtain this singleton by the outside world. 10 public static Singleton getinstance() { 11 return INSTANCE; 12 } 13 } Zheng-Liang Lu Java Programming 242 / 266

Garbage Collection (GC) 1 Java handles deallocation automatically. Heuristics: period or memory stress. GC is the process of looking at the heap memory, identifying whether or not the objects are in use, and deleting the unreferenced objects. An object is said to be unreferenced if the object is no longer referenced by any part of your program. Simply assign null to the reference to make the object unreferenced. So the memory used by these objects can be reclaimed. 1 http://www.oracle.com/webfolder/technetwork/tutorials/obe/ java/gc01/index.html Zheng-Liang Lu Java Programming 243 / 266

finalize() The method finalize() conducts a specific task that will be executed right before the object is reclaimed by GC. For example, closing files and terminating network connections. The finalize() method can be only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) Zheng-Liang Lu Java Programming 244 / 266

Example 1 public class Garbage { 2 private static int numofobjkilled = 0; 3 4 public void finalize() { 5 numofobjkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 10 for (int i = 1; i <= n; i++) 11 new Garbage(); // lots of unreferenced objects 12 System.out.println(numOfObjKilled); 13 } 14 } You may try different number for instance creation. The number of the objects reclaimed by GC is uncertain. Zheng-Liang Lu Java Programming 245 / 266

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, stating that B exists independently from A. For example, knight sword; company employee. If A owns B, then it is a composition, meaning that B has no meaning or purpose in the system without A. For example, house room. Zheng-Liang Lu Java Programming 246 / 266

Example: Lines +2: two Point objects used in one Line object. Zheng-Liang Lu Java Programming 247 / 266

More Examples Circle, Triangle, and Polygon. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. More. Zheng-Liang Lu Java Programming 248 / 266

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 Packages: grouping related types, and providing access controls and name space management. Immutability Enumeration types Inner classes Zheng-Liang Lu Java Programming 249 / 266

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 is a subclass of some class, which is so-called the superclass, by using the extends keyword. For example, B extends A. In semantics, B is a special case of A, or we could say B specializes A. For example, human and dog are two specific types of animals. When both B and C are subclasses of A, we say that A generalizes B and C. (Déjà vu.) Note that Java allows single inheritance only. Zheng-Liang Lu Java Programming 250 / 266

Example 1 class Animal { 2 String name; 3 int weight; 4 5 Animal(String s, int w) { name = s; weight = w; } 6 7 void eat() { weight++; } 8 void exercise() { weight ; } 9 } 10 11 class Human extends Animal { 12 Human(String s, int w) { super(s, w); } 13 void writecode() {} 14 } 15 16 class Dog extends Animal { 17 Dog(String s, int w) { super(s, w); } 18 void watchdoor() {} 19 } Zheng-Liang Lu Java Programming 251 / 266

Class Hierarchy 2 2 See Fig. 3-1 in p. 113 of Evans and Flanagan. Zheng-Liang Lu Java Programming 252 / 266

super Recall that the keyword this is used to refer to the object itself. You can use the keyword super to refer to (non-private) members of the superclass. Note that super() can be used to invoke the constructor of its superclass, just similar to this(). Zheng-Liang Lu Java Programming 253 / 266

Constructor Chaining As the constructor is invoked, the constructor of its superclass is invoked accordingly. You might think that there will be a whole chain of constructors called, all the way back to the constructor of the class Object, the topmost class in Java. So every class is an immediate or a distant subclass of Object. Recall that the method finalize() and tostring() are inherited from Object. tostring(): return a string which can be any information stored in the object. Zheng-Liang Lu Java Programming 254 / 266

Example 1 class A { 2 A() { System.out.println("A is creating..."); } 3 } 4 5 class B extends A { 6 B() { System.out.println("B is creating..."); } 7 // overriding tostring() 8 public String tostring() { return "I am B."; } 9 } 10 11 public class ConstructorChainingDemo { 12 public static void main(string[] args) { 13 B b = new B(); 14 System.out.println(b); 15 } 16 } The println() method (and similar methods) can take an object as input, and invoke tostring() method implicitly. Zheng-Liang Lu Java Programming 255 / 266

Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and also return type, all identical to the previously defined method in its superclass, then we say this newly-defined method overrides the one in the superclass. 3 Recall that method overloading occurs only in the same class. Note that you can invoke the overridden method through the use of the keyword super. 3 Notice that the static methods do not follow this rule. Zheng-Liang Lu Java Programming 256 / 266

Example Zheng-Liang Lu Java Programming 257 / 266

Binding Association of the method definition to the method call is known as binding. The binding which can be resolved at the compilation time is known as static binding or early binding. They are the static, private or final methods. 4 If the compiler is not able to resolve the binding, such binding is known as dynamic binding or late binding. For example, method overriding. 4 We will see the final keyword soon. Zheng-Liang Lu Java Programming 258 / 266

When there are multiple implementations of the method in the inheritance hierarchy, the one in the most derived class (the furthest down the hierarchy) always overrides the others, even if we refer to the object through a reference variable of the superclass type. 5 As you can see in Cat Simon. This is so-called subtype polymorphism. 5 An overridden method in Java acts like a virtual function in C++. Zheng-Liang Lu Java Programming 259 / 266

Polymorphism 6 The word polymorphism literally means many forms. Java allows 4 types of polymorphism: coercion (casting) ad hoc polymorphism (overloading) subtype polymorphism parametric polymorphism (generics) Modeling polymorphism in a programming language lets you create a uniform interface to different kinds of operands, arguments, and objects. 6 Read http://www.javaworld.com/article/3033445/learn-java/ java-101-polymorphism-in-java.html. Zheng-Liang Lu Java Programming 260 / 266

Example: Uniform Interface 1 class Student { 2 void domywork() { / Do not know the detail. /} 3 } 4 5 class HighSchoolStudent extends Student { 6 void writehomework() { 7 System.out.println("Write homework orz"); 8 } 9 10 void domywork() { writehomework(); } 11 } 12 13 class CollegeStudent extends Student { 14 void writereports() { 15 System.out.println("Write reports qq"); 16 } 17 18 void domywork() { writereports(); } 19 } Zheng-Liang Lu Java Programming 261 / 266

1 public class PolymorphismDemo { 2 3 public static void main(string[] args) { 4 HighSchoolStudent h = new HighSchoolStudent(); 5 gostudy(h); 6 CollegeStudent c = new CollegeStudent(); 7 gostudy(c); 8 } 9 10 // uniform interface, multiple implementations 11 // for future extension (scalability) 12 static void gostudy(student s) { 13 s.domywork(); 14 } 15 16 / no need to write these methods 17 static void gostudy(highschoolstudent s) { 18 s.writehomework(); 19 } 20 21 static void gostudy(collegestudent s) { 22 s.writereports(); 23 } 24 / 25 } Zheng-Liang Lu Java Programming 262 / 266

Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties of T (correctness, task performed, etc.). 7,8 7 See https://en.wikipedia.org/wiki/liskov_substitution_principle. 8 Also see https://en.wikipedia.org/wiki/solid_(object-oriented_design). Zheng-Liang Lu Java Programming 263 / 266

Casting Upcasting (widening conversion) is to cast the U object to the T variable. 1 T t = new U(); Downcasting (narrow conversion) is to cast the T variable to a U variable. 1 U u = (U) t; // t is T variable reference to a U object. Upcasting is always allowed, but downcasting is allowed only when a U object is passed to the U-type variable. Java type system makes sure that the referenced object provides services adequate for T type. Zheng-Liang Lu Java Programming 264 / 266

instanceof However, type-checking in compilation time is unsound. The operator instanceof checks if an object reference is an instance of a type, and returns a boolean value. Zheng-Liang Lu Java Programming 265 / 266

1 class T {} 2 class U extends T {} 3 Example 4 public class InstanceofDemo { 5 public static void main(string[] args) { 6 T t1 = new T(); 7 8 System.out.println(t1 instanceof U); // output false 9 System.out.println(t1 instanceof T); // output true 10 11 T t2 = new U(); // upcasting 12 13 System.out.println(t2 instanceof U); // output true 14 System.out.println(t2 instanceof T); // output true 15 16 U u = (U) t2; // downcasting; this is ok. 17 18 u = (U) new T(); // pass the compilation; fail during execution! 19 } 20 } Zheng-Liang Lu Java Programming 266 / 266