Exercise: Singleton 1

Size: px
Start display at page:

Download "Exercise: Singleton 1"

Transcription

1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance = new mysingleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private mysingleton() {} 8 9 // Only way to obtain the singleton from the outside world. 10 public static mysingleton getsingleton() { 11 return Instance; 12 } 13 } To check the uniqueness, you may declare a static field to count the number of mysingleton objects. 1 See any textbook for design patterns. Zheng-Liang Lu Java Programming 249 / 283

2 Garbage Collection (GC) 2 Java handles deallocation automatically. Automatic garbage collection 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-type variable to make the object referenced by this variable unreferenced. So the memory used by an unused object can be reclaimed. You may invoke System.gc() to execute the deallocation procedure. However, frequent invocation of GC is time-consuming. 2 java/gc01/index.html Zheng-Liang Lu Java Programming 250 / 283

3 finalize() Method By writing the finalize() method, you can define specific actions that will be executed while an object is about to be reclaimed by GC. GC runs periodically, checking for objects that are no longer referenced directly or indirectly by other objects. So the finalize() method is only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) Zheng-Liang Lu Java Programming 251 / 283

4 Example 1 public class finalizedemo { 2 public void finalize() { 3 System.out.println("Finalizing!"); 4 } 5 6 public static void main(string[] args) { 7 for (int i = 1; i <= 1e7; i++) { 8 new finalizedemo(); 9 } 10 } 11 } You may try different number of the instances. The number of the objects reclaimed by GC is not deterministic. Zheng-Liang Lu Java Programming 252 / 283

5 HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object. For example, professor department Composition is a specialized form of aggregation and we can call this as a death relationship. For example, house room Zheng-Liang Lu Java Programming 253 / 283

6 Example: Lines on 2D Cartesian Coordinate +2: two Point objects contained in a Line object. Zheng-Liang Lu Java Programming 254 / 283

7 More Examples More geometric objects, say Circle, Triangle, and Polygon. Complex number (a + bi) equipped with + and so on. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. Zheng-Liang Lu Java Programming 255 / 283

8 More Relationships Between Classes So far, we have seen how to define classes and also create objects. Recall that classes would be little more than a convention for organizing code. Moreover, there exist the relationships among classes: inheritance: passing down states and behaviors from parent classes to its child classes interfaces: specifying the methods as an interface to the outside world for classes packages: grouping related types, providing access protection and name space management Zheng-Liang Lu Java Programming 256 / 283

9 Inheritance Different kinds of objects often share common properties with each other. For example, mountain bikes, road bikes, and tandem bikes all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet, each also defines additional features that make themselves more specific. For simplicity, let A be a class defined as follows: 1 class A { 2 int x = 1; 3 void foo() { 4 System.out.println("This is from A."); 5 } 6 } Zheng-Liang Lu Java Programming 257 / 283

10 Example 1 class B extends A { 2 int y = 2; 3 void hoo() { 4 System.out.println("This is from B."); 5 } 6 } 7 8 public class inheritancedemo { 9 public static void main(string[] args) { 10 A a = new A(); 11 a.foo(); 12 System.out.println("a.x = " + a.x); B b = new B(); 15 b.foo(); 16 b.hoo(); 17 System.out.println("b.x = " + b.x); 18 System.out.println("b.y = " + b.y); 19 } 20 } Zheng-Liang Lu Java Programming 258 / 283

11 Note that a subclass inherits those members from its superclass not designated as private. 1 class A { 2 private int x = 1; 3 private void foo() {... } 4 } 5 6 class B extends A {... } 7 8 public class inheritancemain { 9 public static void main(string[] args) { B b = new B(); 12 b.foo(); // Oops, invisible! 13 b.hoo(); 14 System.out.println("b.x = " + b.x); // Oops, invisible! 15 System.out.println("b.y = " + b.y); 16 } 17 } Zheng-Liang Lu Java Programming 259 / 283

12 First IS-A Relationship Object-oriented programming allows classes to inherit commonly used states and behaviors from other classes. So classes exist in a hierarchy. A class can be declared as a subclasses of another class, which is called superclass, by using the extends keyword. So we can say that a subclass specializes its superclass. Equivalently, one subclass is a special case of the superclass. Note that a class can extend only one other class. Each superclass has the potential for an unlimited number of subclasses. Zheng-Liang Lu Java Programming 260 / 283

13 Class Hierarchy 3 3 See Fig. 3-1 in p. 113 of Evans and Flanagan. Zheng-Liang Lu Java Programming 261 / 283

14 The super Keyword Recall that the keyword this is used to refer to the object itself. You can use the keyword super to refer to members of the superclass. Note that this() and super() are used as the constructor of the current class and that of its superclass, respectively. Make sure all the constructor are invoked in the first line in the constructors. Zheng-Liang Lu Java Programming 262 / 283

15 Constructor Chaining If a subclass constructor invokes a constructor of its superclass, 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 class. Zheng-Liang Lu Java Programming 263 / 283

16 1 class A { 2 int x; 3 Example 4 A() { 5 System.out.println("A..."); 6 } 7 8 A(int x) { 9 this(); 10 this.x = x; 11 } 12 } class B extends A { 15 B() { 16 super(10); 17 System.out.println("B..."); 18 } 19 } Zheng-Liang Lu Java Programming 264 / 283

17 23 public class constructorchainingdemo { 24 public static void main(string[] args) { 25 B b = new B(); 26 System.out.println(b.x); 27 } 28 } Zheng-Liang Lu Java Programming 265 / 283

18 Field Hiding If one field whose name is same to the field inherited from the superclass, then the newly field hides that of the superclass. In other words, the shadowed field of the superclass cannot be referenced by its simple name. Instead, the field must be accessed through the key word super. Zheng-Liang Lu Java Programming 266 / 283

19 Example 1 class A { 2 int x = 1; 3 } 4 5 class B extends A { 6 int x = 2; 7 8 int getxfroma() { 9 return super.x; 10 } 11 } class fieldhidingdemo { 14 public static void main(string[] args) { 15 B b = new b(); 16 System.out.println(b.x); // output 2 17 System.out.println(b.getXfromA()); // output 1 18 } 19 } Zheng-Liang Lu Java Programming 267 / 283

20 Method Overriding When a class defines an instance method using the same name, return type, and parameters as a method in its superclass, that method overrides the method of the superclass. Key elements: inheritance, exactly same method definition, including the return type Recall that we could declare overloaded methods, that is, the methods with different signatures within a class. Key elements: in the same class, different signatures Similarly if your method overrides one of its superclass s methods, you can invoke the overridden method through the use of the keyword super. Zheng-Liang Lu Java Programming 268 / 283

21 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. 4 4 An overridden method in Java acts like a virtual function in C++. Zheng-Liang Lu Java Programming 269 / 283

22 Example Zheng-Liang Lu Java Programming 270 / 283

23 Binding Association of method definition to the method call is known as binding. The binding which can be resolved at compile time by compiler is known as static binding or early binding. They are the static, private and final methods. Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. When compiler is not able to resolve the binding at compile time, such binding is known as dynamic binding or late binding. For example, method overriding. Zheng-Liang Lu Java Programming 271 / 283

24 Polymorphism In OO design, the word polymorphism, which literally means many forms, refers to the ability of reference variables to take different forms. The Liskov Substitution Principle states that one variable associated with the declared type can be assigned an instance from any direct or indirect subclass of that type. 5 Let U be a a subtype of T. Then T variables may refer to U objects. 5 It is a semantic rather than merely syntactic relation because it intends to guarantee semantic interoperability of types in a hierarchy, object types in particular. See Zheng-Liang Lu Java Programming 272 / 283

25 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 the T variable refer to a real U object. This involves type compatibility by JVM during program execution. Zheng-Liang Lu Java Programming 273 / 283

26 instanceof Operator The operator instanceof allows us to test whether or not a reference variable is compatible to the object. If not compatible, then JVM will throw an exception ClassCastException. 6 6 We will see the exceptions later. Zheng-Liang Lu Java Programming 274 / 283

27 1 class T {} 2 3 class U extends T {} 4 Example 5 public class instanceofdemo { 6 public static void main(string[] args) { 7 T t1 = new T(); 8 9 if (t1 instanceof U) 10 System.out.println("t1 is an instance of U."); 11 else 12 System.out.println("t1 is not an instance of U."); if (t1 instanceof Object) 15 System.out.println("t1 is an instance of Object."); 16 else 17 System.out.println("t1 is not an instance of Object. "); Zheng-Liang Lu Java Programming 275 / 283

28 22 23 T t2 = new U(); // Upcasting if (t2 instanceof U) 26 System.out.println("t2 is an instance of U."); 27 else 28 System.out.println("t2 is not an instance of U."); U u = (U) t2; // Downcasting; this is ok u = (U) new T(); // Oops, this is now allowed. 33 } 34 } Zheng-Liang Lu Java Programming 276 / 283

29 Exercise Zheng-Liang Lu Java Programming 277 / 283

30 1 public class animalfamilydemo { 2 public static void main(string[] args) { 3 Dog d = new Dog(); 4 d.sleep(); 5 d.eat(); 6 d.watchdoor(); 7 8 Cat c = new Cat(); 9 c.sleep(); 10 c.eat(); 11 c.chaselittlething(); Animal a = d; // Upcasting 14 a.sleep(); 15 a.eat(); 16 a.watchdoor(); // Oops, invisible! 17 a.chaselittlething(); // Oops, invisible! d = (Dog) a; // Downcasting 20 d.watchdoor(); // Works! 21 } 22 } Zheng-Liang Lu Java Programming 278 / 283

31 Field Hiding with Polymorphism You can refer to hidden fields simply by casting an object to a variable of the appropriate superclass. 1 class T { 2 int x = 1; 3 } 4 5 class U extends T { 6 int x = 2; 7 } 8 9 public class fieldhidingdemo { 10 public static void main(string[] args) { 11 U u = new U(); 12 System.out.println(u.x); // output 2 13 T t = u; 14 System.out.println(t.x); // output 1 15 } 16 } Zheng-Liang Lu Java Programming 279 / 283

32 Method Overriding with Polymorphism However, you cannot invoke overridden methods by upcasting. JVM calls the appropriate method for the object. Method lookup starts from the bottom of the class hierarchy to the top. Always looking for the most specific method body. These methods are referred to as virtual methods. This mechanism preserves the behaviors of the objects and the superclass type variables play the role of placeholders. Zheng-Liang Lu Java Programming 280 / 283

33 Example Imagine that we have a zoo with some animals. 1 class Animal { 2 String name; 3 void speak() {} 4 } 5 6 class Dog extends Animal { 7 Dog(String name) { 8 this.name = name; 9 } 10 void speak() { 11 System.out.println(name + ": wooooo"); 12 } 13 } class Cat extends Animal { 16 Cat(String name) { 17 this.name = name; 18 } 19 void speak() { Zheng-Liang Lu Java Programming 281 / 283

34 20 System.out.println(name + ": mewwwww"); 21 } 22 } class Bird extends Animal { 25 Bird(String name) { 26 this.name = name; 27 } 28 void speak() { 29 System.out.println(name + ": ziiii"); 30 } 31 } public class polymorphismdemo { 34 public static void main(string[] args) { 35 Animal[] zoo = new Animal[6]; zoo[0] = new Dog("Dog 1"); 38 zoo[1] = new Cat("Cat 1"); 39 zoo[2] = new Cat("Simon"); 40 zoo[3] = new Bird("B1"); 41 zoo[4] = new Bird("B2"); Zheng-Liang Lu Java Programming 282 / 283

35 42 zoo[5] = new Bird("B3"); for (int i = 0; i < zoo.length; i++) { 45 zoo[i].speak(); 46 } 47 } 48 } Zheng-Liang Lu Java Programming 283 / 283

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

Example: Count of Points

Example: Count of Points 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;

More information

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. 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,

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance 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

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 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

More information

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. 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 its return type, all identical

More information

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. 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

More information

Subtype Polymorphism

Subtype Polymorphism 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

More information

Exercise. Zheng-Liang Lu Java Programming 273 / 324

Exercise. Zheng-Liang Lu Java Programming 273 / 324 Exercise Zheng-Liang Lu Java Programming 273 / 324 1 public class AnimalFamilyDemo { 2 public static void main(string[] args) { 3 Dog d = new Dog(); 4 d.sleep(); 5 d.eat(); 6 d.watchdoor(); 7 8 Animal

More information

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

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug., 2016 U Hou Lok Java Programming 1 / 51 A Math Toolbox: Math Class The

More information

Example: Fibonacci Numbers

Example: Fibonacci Numbers Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers

More information

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 304 Fall Department of Computer Science & Information Engineering National Taiwan University Java Programming 2 Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Java2 304 Fall 2018 1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Implements vs. Extends When Defining a Class

Implements vs. Extends When Defining a Class Implements vs. Extends When Defining a Class implements: Keyword followed by the name of an INTERFACE Interfaces only have method PROTOTYPES You CANNOT create on object of an interface type extends: Keyword

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

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

Recursion 1. Recursion is the process of defining something in terms of itself. Recursion 1 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

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

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object Unit 8 Inheritance Summary Inheritance Overriding of methods and polymorphism The class Object 8.1 Inheritance Inheritance in object-oriented languages consists in the possibility of defining a class that

More information

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

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

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

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

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

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level CSE1720 Click to edit Master Week text 08, styles Lecture 13 Second level Third level Fourth level Fifth level Winter 2014! Thursday, Feb 27, 2014 1 General Info Continuation of Chapter 9 Read Chapter

More information

Java Programming 2. Zheng-Liang Lu. Java2 306 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 Java Programming 2 Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Java2 306 Fall 2018 1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Lecture 4: Extending Classes. Concept

Lecture 4: Extending Classes. Concept Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Hierarchy. Lecture 6: OOP, autumn 2003 Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 10.1 10.3 1 Interface Hierarchies Inheritance can

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Inheritance and Polymorphism. CS180 Fall 2007

Inheritance and Polymorphism. CS180 Fall 2007 Inheritance and Polymorphism CS180 Fall 2007 Definitions Inheritance object oriented way to form new classes from pre-existing ones Superclass The parent class If class is final, cannot inherit from this

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University 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

More information

CS Programming I: Inheritance

CS Programming I: Inheritance CS 200 - Programming I: Inheritance Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Inheritance

More information

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

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

type conversion polymorphism (intro only) Class class

type conversion polymorphism (intro only) Class class COMP 250 Lecture 33 type conversion polymorphism (intro only) Class class Nov. 24, 2017 1 Primitive Type Conversion double float long int short char byte boolean non-integers integers In COMP 273, you

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Binghamton University. CS-140 Fall Dynamic Types

Binghamton University. CS-140 Fall Dynamic Types Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

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

Programming in the Large II: Objects and Classes (Part 2) 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

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Lecture 12 Summary Inheritance Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Multiplicity 1 By the end of this lecture, you will

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Lecture 6 Introduction to Objects and Classes

Lecture 6 Introduction to Objects and Classes Lecture 6 Introduction to Objects and Classes Outline Basic concepts Recap Computer programs Programming languages Programming paradigms Object oriented paradigm-objects and classes in Java Constructors

More information

Create a Java project named week10

Create a Java project named week10 Objectives of today s lab: Through this lab, students will examine how casting works in Java and learn about Abstract Class and in Java with examples. Create a Java project named week10 Create a package

More information

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers Code Shape II Objects & Classes Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 L-1 Administrivia Semantics/type check due next Thur. 11/15 How s it going? Reminder: if you want

More information

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

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

Overriding Variables: Shadowing

Overriding Variables: Shadowing Overriding Variables: Shadowing We can override methods, can we override instance variables too? Answer: Yes, it is possible, but not recommended Overriding an instance variable is called shadowing, because

More information

C10: Garbage Collection and Constructors

C10: Garbage Collection and Constructors CISC 3120 C10: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/5/2018 CUNY Brooklyn College 1 Outline Recap OOP in Java: composition &

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Inheritance, polymorphism, interfaces

Inheritance, polymorphism, interfaces Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods. Final Exam Polymorphism Time: Thursday Dec 13 @ 4:30-6:30 p.m. November 26, 2007 Location: Curtiss Hall, room 127 (classroom) ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Subclasses, Superclasses, and Inheritance

Subclasses, Superclasses, and Inheritance Subclasses, Superclasses, and Inheritance To recap what you've seen before, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass.

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

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

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Introductory Programming Inheritance, sections

Introductory Programming Inheritance, sections Introductory Programming Inheritance, sections 7.0-7.4 Anne Haxthausen, IMM, DTU 1. Class hierarchies: superclasses and subclasses (sections 7.0, 7.2) 2. The Object class: is automatically superclass for

More information

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Written by John Bell for CS 342, Spring 2018

Written by John Bell for CS 342, Spring 2018 Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors

More information

CSA 1019 Imperative and OO Programming

CSA 1019 Imperative and OO Programming CSA 1019 Imperative and OO Programming Object Oriented III Mr. Charlie Abela Dept. of of Artificial Intelligence Objectives Getting familiar with Method Overriding Polymorphism Overriding Vs Vs Overloading

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (A) Name:. Status:

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4(b): Inheritance & Polymorphism Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword

More information

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information