IST311. Advanced Issues in OOP: Inheritance and Polymorphism
|
|
- Ezra French
- 6 years ago
- Views:
Transcription
1 IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang 1
2 Context: Object Oriented Modeling / Programming Entities in the real world Programmers Developers Create classes Abstracting the real world 2
3 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These geometric classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use object inheritance. 3 3
4 4 Example1: Superclasses & Subclasses
5 1 Example1: Superclasses and Subclasses 2 public abstract class GeometricObject private string color = "White"; private bool filled; private DateTime datecreated; // Construct a default GeometricObject protected internal GeometricObject() datecreated = DateTime.Now; // Filled property: return true if opaque public bool Filled get return filled; set this.filled = value; // DateCreated property public DateTime DateCreated get return datecreated; 3 // create obj with color and filled value protected internal GeometricObject( string colorvalue, bool filledvalue) datecreated = DateTime.Now; Color = colorvalue; Filled = filledvalue; // Color property public string Color get return color; set this.color = value; // Return a string representing this object public override string ToString() return "\tgeometricobject[" + " created on: " + DateCreated + ", color: " + Color + ", filled: " + Filled + " ] "; // Abstract method Area public abstract double Area(); // Abstract method Perimeter public abstract double Perimeter(); virtual is a C# idiom used to emphasize that a method is not abstract. Only methods explicitly marked as either: virtual or abstract can be overridden!
6 Example1: Superclasses and Subclasses public class Circle : GeometricObject private double radius = 1; public Circle() public Circle(double radiusvalue) : base() Radius = radiusvalue; public Circle(double radiusvalue, string colorvalue, bool filledvalue) : base(colorvalue, filledvalue) Radius = radiusvalue; //Color = colorvalue; //Filled = filledvalue; // Radius property public double Radius get return radius; set this.radius = value; // calculate Perimeter public override double Perimeter() return 2 * radius * Math.PI; /* Print Circle info */ public void PrintCircle() Console.WriteLine(ToString() + " Circle created on: " + DateCreated + " and the radius is " + Radius); public override string ToString() return "Circle [" + Color + " Radius: " + Radius + " Perimeter: " + String.Format("0:F2",Perimeter()) + " Area: " + String.Format("0:F2", Area() ) + " ]" + "\n" + base.tostring(); // calculate Area public override double Area() return radius * radius * Math.PI; 6 // calculate Diameter public double Diameter() return 2 * radius;
7 Example1: Superclasses and Subclasses public class Rectangle : GeometricObject private double width; private double height; public Rectangle() public Rectangle(double widthvalue, double heightvalue) : base() Width = widthvalue; Height = heightvalue; public Rectangle(double widthvalue, double heightvalue, string colorvalue, bool filledvalue) : base(colorvalue, filledvalue) Width = widthvalue; Height = heightvalue; // setcolor(colorvalue); // setfilled(filledvalue); public double Width get return width; set this.width = value; public double Height get return height; set this.height = value; //calculate Area public override double Area() return Width * Height; // calculate perimeter public override double Perimeter() return 2 * (Width + Height); public override string ToString() return "Rectangle [ Width: " + Width + ", Height: " + Height + ", Perimeter: " + String.Format("0:F2", Perimeter() ) + ", Area: " + String.Format("0:F2", Area()) + " ]" + "\n" + base.tostring(); 5 4
8 Example1: Superclasses and Subclasses Testing GeometricObject1, Circle4 and Rectangle1 Classes static void Main(string[] args) //GeometricObject g = new GeometricObject(); //TRY - Error! Circle c1 = new Circle(); Console.WriteLine(c1); Circle c2 = new Circle(2, "Red", true); Console.WriteLine( c2 ); Rectangle r1 = new Rectangle(1, 2, "Blue", true); Console.WriteLine( r1 ); Console.ReadLine(); Console Circle [White Radius: 1 Perimeter: 6.28 Area: 3.14 ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: White, filled: False] Circle [Red Radius: 2 Perimeter: Area: ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: Red, filled: True] Rectangle [ Width: 1, Height: 2, Perimeter: 6.00, Area: 2.00 ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: Blue, filled: True] 8 8
9 Invoking Superclass Constructors Constructors could be invoked explicitly or implicitly. Explicit calls use the base keyword : base () : base (arg1, arg2, ) In implicit calls (the keyword base is not used), the superclass no-arg constructor is automatically invoked. If used, the statement :base() or :base(arguments) must appear in the first line of the subclass constructor. 9 9
10 Superclass s Constructor Is Always Invoked A constructor may invoke a local overloaded constructor or its superclass s constructor(s). If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, public A() is equivalent to public A() : base() public A(double d) // some statements is equivalent to public A(double d) :base() // some statements 10 10
11 Using the Keyword base The keyword base refers to the superclass of the class in which base appears. base keyword can be used in two ways: To call a superclass constructor To call a superclass method Super-class base. this. Sub-class 11 11
12 Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override methods of the superclass Super-class Sub-class 12 12
13 Calling Superclass Methods You could invoke an ancestor s method as follow 13 // Override ancestor s ToString method public override string ToString() return "Circle [" + Color + " Radius: " + Radius + " Perimeter: " + String.Format("0:F2",Perimeter() ) + " Area: " + String.Format("0:F2", Area() ) + " ]" + "\n" + base.tostring(); 1
14 NOTE An instance method can be overridden only if it is accessible. A private method cannot be overridden by a subclass because it is not accessible outside its own class. A static method cannot be overridden
15 The Object Class and Its Methods Object obj; 15 15
16 The ToString() method in Object ToString() method returns a string representation of the object. The default implementation returns a string holding: 1. Namespace. 2. A class name of which the object is an instance, Loan boatloan = new Loan(); Console.WriteLine ( boatloan.tostring() ); For this example we get something like: MyNameSpace.Loan You should override the ToString method so that it returns a more meaningful string representation of the object
17 17 Polymorphism, Dynamic Binding and Generic Programming public static void Main(string[] args) Show(new GraduateStudent()); Show(new Student()); Show(new Person()); Show(new object()); // public static void Show (object x) Console.WriteLine(x.ToString()); // internal class GraduateStudent : Student public override string ToString() return "Grad. Student"; internal class Student : Person public override string ToString() return "Student"; internal class Person : object public override string ToString() return "Person"; Polymorphic method Show takes parameters of various types. A method that can be applied to values of different types is called a polymorphic function. In our example which implementation of the ToString() method is used will be determined dynamically by the.net runtime environment. This capability is known as dynamic binding. Console: Grad. Student Student Person System.Object
18 Method Matching (Overloading) The compiler finds a matching method according to: 1. parameter type, 2. number of parameters, and 3. order of the parameters at compilation time. Example of different invocation of the pay method bill.paywith ( ) bill.paywith ("Visa", " " ); bill.paywith ("two cows" ); 18 18
19 Casting Objects Casting can be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement Show( new Student() ); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to: Object obj = new Student(); // implicit casting Show(obj); The statement Object obj = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object.
20 Why Casting Is Necessary? 1. To tell the compiler that an object should be treated as of a particular type you use an explicit casting. 2. In the example below, msg is a block of binary data that could be interpreted in different ways depending on the casting applied on it. Object msg = ChunkOfBinaryData(); Voice v = (Voice) msg;... Sms s = (Sms) msg;... e = ( ) msg;... Morse m = (Morse) msg;
21 Casting from Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Apple x = (Apple)fruit; Orange y = (Orange)fruit; double d = ; Specializing int n = (int) d; Observation: Assume fruit is a banana. Both castings will fail. The numeric example works.
22 The is Operator Use the instanceof operator to test whether an object is an instance of a given class: object myobject = new Circle(); // Some lines of code here... // Perform casting if myobject is an instance of Circle if (myobject is Circle) Console.WriteLine("The circle diameter is " + ((Circle)myObject).Diameter() ); //
23 The Equals Method The equals() method compares the contents of two objects object1.equals( object2 ) The default implementation of the equals method in the Object class is as follows: public bool Equals ( Object otherobject ) return ( this == otherobject ); The Equals method could be overridden in our Circle example as: public override bool Equals ( Object otherobject ) if (otherobject is Circle) return this.radius == ((Circle)otherObject).Radius; else return false;
24 NOTE The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The Equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects
25 The protected Modifier The protected modifier can be applied on data and methods in a class. A protected data or method in a public class can be accessed by its subclasses. private internal (no modifier is used) protected public Visibility increases 25 25
26 Accessibility Summary Modifier on members in a class Accessed from the same class Accessed from the same namespace Accessed from a subclass Accessed from a different namespace public Yes Yes Yes Yes protected Yes Yes Yes No internal Yes Yes Yes No private Yes No No No 26 26
27 Visibility Modifiers Namespace n1 public class C1 public int x; protected int y; int z; private int u; protected void m() public class C2 C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); Nanmesape n2 public class C3 : C1 can access x; can access y; can access z; cannot access u; public class C4 : C1 can access x; can access y; cannot access z; cannot access u; public class C5 C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; can invoke m(); can invoke m(); cannot invoke o.m(); 27 27
28 A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass. private default (no modifier is used) protected public Changes of visibility are valid in this direction Changes of visibility are invalid in this direction 28 28
29 sealed Keyword Modifiers (private, public, protected, internal) are used on classes, methods, and class variables. A sealed class is one that cannot be extended by subclassing. A sealed method cannot be overridden by its subclasses
30 30 30 Appendix A. Using Eclipse Tool Bar to code a POJO (Plain Old Java Object)
Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber
Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More informationLesson11-Inheritance-Abstract-Classes. The GeometricObject case
Lesson11-Inheritance-Abstract-Classes The GeometricObject case GeometricObject class public abstract class GeometricObject private string color = "White"; private DateTime datecreated = new DateTime(2017,
More informationInheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University
Inheritance and Polymorphism CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Model classes with similar properties and methods: Circles, rectangles
More information25. 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 informationChapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism 1 Motivations OOP is built on three principles: Encapsulation (classes/objects, discussed in chapters 9 and 10), Inheritance, and Polymorphism. Inheritance: Suppose
More informationCS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and
More informationCOMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed
1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every
More informationInheritance (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 informationChapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9
Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter
More informationChapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1 Motivations Suppose you will define classes
More informationLecture 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 informationCS-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 informationChapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {
Chapter 21- Using Generics Case Study: Geometric Bunch In this example a class called GeometricBunch is made to wrap around a list of GeometricObjects. Circle and Rectangle are subclasses of GeometricObject.
More information24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini
24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 11: Inheritance and Polymorphism Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad
More information22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming
More informationCH. 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 informationConstructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Constructor Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The
More informationCS1150 Principles of Computer Science Objects and Classes
CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8
More informationInheritance 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 informationCISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College
CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype
More informationAdvanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition
11 Features Advanced Object-Oriented Programming C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition Chapter Objectives 2 Chapter
More informationWhat is an interface? Why is an interface useful?
IST311 Interfaces IST311 / 602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang 1 What is an interface?
More informationIntroductory 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 informationChapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism rights reserved. 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the
More informationObject 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 informationITI 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 informationITI 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 informationCOMP200 - Object Oriented Programming: Test One Duration - 60 minutes
COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;
More informationUse the scantron sheet to enter the answer to questions (pages 1-6)
Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object
More informationInheritance (Deitel chapter 9)
Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance
More informationHomework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace
More informationHAS-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 informationBinghamton 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 informationComputer 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 informationCOMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed
1 1 COMP200 ABSTRACT CLASSES OOP using Java, from slides by Shayan Javed Abstract Classes 2 3 From the previous lecture: public class GeometricObject { protected String Color; protected String name; protected
More informationProgramming 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 informationObject Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods
Object Oriented System Development Paradigm Sunnie Chung CIS433 System Analysis Methods OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents
More informationWhat 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 informationJava 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 informationChapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces rights reserved. 1 Motivations You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions,
More informationJava Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
More informationPractice 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 informationIntroduction to Inheritance
Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits
More informationMore About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario
More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and
More informationInheritance -- 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 informationThe software crisis. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:
More informationCSA 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 informationClasses 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 informationINHERITANCE & 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 informationCMSC 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 informationComputer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7
Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer
More informationInheritance and Polymorphism
Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab
More informationGraphical 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 informationCSC330 Object Oriented Programming. Inheritance
CSC330 Object Oriented Programming Inheritance Software Engineering with Inheritance Can customize derived classes to meet needs by: Creating new member variables Creating new methods Override base-class
More informationMaking New instances of Classes
Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using
More informationAbstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof
Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation
More informationMore 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 informationInheritance and object compatibility
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can
More informationIn this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.
Jordan University Faculty of Engineering and Technology Department of Computer Engineering Object-Oriented Problem Solving: CPE 342 Lab-8 Eng. Asma Abdel Karim In this lab, you will be given the implementation
More informationJava Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding
Java Class Design Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Objectives Implement encapsulation Implement inheritance
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int
More informationBig software. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting
More informationLecture 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 informationInheritance 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 informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More informationMore 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 informationChapter 6: Inheritance
Chapter 6: Inheritance EECS 1030 moodle.yorku.ca State of an object final int WIDTH = 3; final int HEIGTH = 4; final int WEIGHT = 80; GoldenRectangle rectangle = new GoldenRectangle(WIDTH, HEIGHT, WEIGHT);
More information1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'
Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java
More informationCOMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code
COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,
More informationChapter 9 - Object-Oriented Programming: Polymorphism
Chapter 9 - Object-Oriented Programming: Polymorphism Polymorphism Program in the general Introduction Treat objects in same class hierarchy as if all superclass Abstract class Common functionality Makes
More informationHAS-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 informationChapter 14 Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationCMSC 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 informationCMSC131. 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 informationClass, 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 information25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
25. Interfaces Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Definition The Comparable Interface Interfaces vs. Abstract Classes Creating Custom Interfaces References Definition Definition Sometimes
More informationProgramming 2. Inheritance & Polymorphism
Programming 2 Inheritance & Polymorphism Motivation Lame Shape Application public class LameShapeApplication { Rectangle[] therects=new Rectangle[100]; Circle[] thecircles=new Circle[100]; Triangle[] thetriangles=new
More informationChapter 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 informationHAS-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 informationFirst 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 informationArgument 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 informationPolymorphism and Interfaces. CGS 3416 Spring 2018
Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that
More informationLecture Notes Chapter #9_c Abstract Classes & Interfaces
Lecture Notes Chapter #9_c Abstract Classes & Interfaces Abstract Classes parent class child class more abstract more concrete, i.e., less abstract abstract class o class with an abstract modifier o class
More informationMotivations. Chapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations You have learned how to write simple
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationContents. 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 informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationCSE 143 Lecture 20. Circle
CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public
More informationPolymorphism. Polymorphism. CSC 330 Object Oriented Programming. What is Polymorphism? Why polymorphism? Class-Object to Base-Class.
Polymorphism CSC 0 Object Oriented Programming Polymorphism is considered to be a requirement of any true -oriented programming language (OOPL). Reminder: What are the other two essential elements in OOPL?
More informationReusing Classes. Hendrik Speleers
Hendrik Speleers Overview Composition Inheritance Polymorphism Method overloading vs. overriding Visibility of variables and methods Specification of a contract Abstract classes, interfaces Software development
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn how to describe objects and classes and how to define
More informationInheritance. Software Engineering with Inheritance. CSC330 Object Oriented Programming. Base Classes and Derived Classes. Class Relationships I
CSC0 Object Oriented Programming Inheritance Software Engineering with Inheritance Can customize derived classes to meet needs by: Creating new member variables Creating new methods Override base-class
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationCSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:
CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Thursday 12:00 PM 2:00 PM Friday 8:30 AM 10:30 AM OR request appointment via e-mail
More informationComputer Science 210: Data Structures
Computer Science 210: Data Structures Summary Today writing a Java program guidelines on clear code object-oriented design inheritance polymorphism this exceptions interfaces READING: GT chapter 2 Object-Oriented
More informationLecture 18 CSE11 Fall 2013 Inheritance
Lecture 18 CSE11 Fall 2013 Inheritance What is Inheritance? Inheritance allows a software developer to derive a new class from an existing one write code once, use many times (code reuse) Specialization
More information