Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9
|
|
- Meghan Johnson
- 6 years ago
- Views:
Transcription
1 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 13 Graphics 10.4, Interfaces Chapter 14 Event-Driven Programming Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 17 Exceptions and Assertions Chapter 18 Binary I/O 1
2 To develop a subclass from a superclass through inheritance ( 9.2). To invoke the superclass s constructors and methods using the super keyword ( 9.3). To override methods in the subclass ( 9.4). To distinguish differences between overriding and overloading ( 9.5). To comprehend polymorphism, dynamic binding, and generic programming ( 9.7). To describe casting and explain why explicit downcasting is necessary ( 9.8). To restrict access to data and methods using the protected visibility modifier ( 9.11). To declare constants, unmodifiable methods, and nonextendable classes using the final modifier ( 9.12). (Optional) To understand the effect of hiding data fields and static methods ( 9.14). (Optional) To initialize data using initialization blocks and to distinguish between instance initialization and static initialization blocks ( 9.15). To store, retrieve, and manipulates objects in an ArrayList,Vector ( 9.9). 2
3 GeometricObject -color: String -filled: boolean -datecreated: java.util.date +GeometricObject() +getcolor(): String +setcolor(color: String): void +isfilled(): boolean +setfilled(filled: boolean): void +getdatecreated(): java.util.date +tostring(): String The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the datecreated. Returns a string representation of this object. Circle -radius: double +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getarea(): double +getperimeter(): double +getdiameter(): double Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +getwidth(): double +setwidth(width: double): void +getheight(): double +setheight(height: double): void +getarea(): double +getperimeter(): double 3
4 No. They are not inherited. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They are invoked explicitly or implicitly. Explicitly using the super keyword. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked.[super()] A subclass inherits accessible data fields and methods from its superclass. 4
5 A constructor may invoke an overloaded constructor (this([args])) or its superclass s constructor (super([args])). 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() { super(); public A(double d) { // some statements is equivalent to public A(double d) { super(); // some statements 5
6 The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: To call a superclass constructor: super([args]); To call a superclass method: super.m(); 6
7 You must use the keyword super to call the superclass constructor. Invoking a superclass constructor s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor. 7
8 Constructing an instance of a class invokes all the superclasses constructors along the inheritance chain. This is called constructor chaining. 1.class Person { 2. public Person() { 3. System.out.println("(1) Person's no-arg constructor is invoked"); 4.class Employee extends Person { 5. public Employee() { 6. this("(2) Invoke Employee s overloaded constructor"); 7. System.out.println("(3) Employee's no-arg constructor is invoked"); 8. public Employee(String s) { 9. System.out.println(s); super(); super(); 10. public class Faculty extends Employee { 11. public Faculty() { 12. System.out.println("(4) Faculty's no-arg constructor is invoked"); 13. public static void main(string[] args) { 14. new Faculty(); (1) Person's no-arg constructor is invoked (2) Invoke Employee s overloaded constructor (3) Employee's no-arg constructor is invoked (4) Faculty's no-arg constructor is invoked 8
9 Find out the errors in the program: class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); public class Apple extends Fruit { public Apple(){ super(); ว ธ แก ไข 1. แก ท คลาส Apple 2. แก ท คลาส Fruit 9
10 A subclass extends properties and methods from the superclass. You can also: Add new properties (data fields) Add new methods Override the methods of the superclass 10
11 GeometricObject -color: String -filled: boolean -datecreated: java.util.date +GeometricObject() +getcolor(): String +setcolor(color: String): void +isfilled(): boolean +setfilled(filled: boolean): void +getdatecreated(): java.util.date +tostring(): String The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the datecreated. Returns a string representation of this object. Circle -radius: double +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getarea(): double +getperimeter(): double +getdiameter(): double Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +getwidth(): double +setwidth(width: double): void +getheight(): double +setheight(height: double): void +getarea(): double +getperimeter(): double เพ มเมธอดลงใน Circle ช อ printcircle() ซ งท าการเร ยกใช เมธอด getdatecreated() 11
12 You could rewrite the printcircle() method in the Circle class as follows: GeometricObject -color: String -filled: boolean -datecreated: java.util.date +GeometricObject() +getcolor(): String +setcolor(color: String): void +isfilled(): boolean +setfilled(filled: boolean): void +getdatecreated(): java.util.date +tostring(): String public class Circle extends GeometricObject{ public void printcircle() { System.out.println("The circle is created " + super.getdatecreated() + " and the radius is " + radius); //ไม จ าเป นต องเร ยกผ านค าส ง super 12
13 A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the tostring method defined in GeometricObject */ public String tostring() { return super.tostring() + "\nradius is " + radius; 13
14 An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. 14
15 1. class A{ 2. private void m(){ 3. System..out.println( call from A ); public void m2(){ 6. m(); class B extends A{ 10. private void m(){ 11. System.out.println( call from B ); public void m2(){ 14. m(); public class TestOveridePrivateMethod { 18. public static void main(string[] args) { 19. B obj = new B(); 20. obj.m2();//call from B แทรกลงไปก อน line 15 ด วย super.m(); // can invoke or not? 15
16 class B { public void p(int i) { class A extends B { // This method overrides the method in B public void p(int i) { System.out.println(i); public class Test { public static void main(string[] args) { A a = new A(); a.p(10); inheritance Same name Same signature Same return type class B { public void p(int i) { class A extends B { // This method overloads the method in B public void p(double i) { System.out.println(i); public class Test { public static void main(string[] args) { A a = new A(); a.p(10); Same class, inheritance Same name different signature No relate to return type 16
17 Every class in Java is descended from the java.lang.object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. public class Circle {... Equivalent public class Circle extends Object {... 17
18 The tostring() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object (hash code in hexadecimal). Loan loan = new Loan(); System.out.println(loan.toString()); The code displays something like Loan@15037e5. This message is not very helpful or informative. Usually you should override the tostring method so that it returns a digestible string representation of the object. 18
19 class Person extends Object { public String tostring() { return "Person"; class Student extends Person { public String tostring() { return "Student"; class GraduateStudent extends Student { public class PolymorphismDemo { public static void m(object x) { System.out.println(x.toString()); public static void main(string[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); Method m takes a parameter of the Object type. You can invoke it with any object. An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. When the method m(object x) is executed, the argument x s tostring method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object have their own implementation of the tostring method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. 19
20 Matching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time.(ด data type) A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime.(ด ตรง new) 20
21 Dynamic binding works as follows: Suppose an object o is an instance of classes C 1, C 2,..., C n-1, and C n, where C 1 is a subclass of C 2, C 2 is a subclass of C 3,..., and C n-1 is a subclass of C n. That is, C n is the most general class, and C 1 is the most specific class. In Java, C n is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C 1, C 2,..., C n-1 and C n, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked. Since o is an instance of C 1, o is also an instance of C 2, C 3,, C n-1, and C n C n C n C 2 C 1 Object C 1 o = new C 1 (); o.p(); 21
22 Object C n-1... C 2 +p() print C2 C 1 o = new C 1 (); o.p(); C 2 o = new C 2 (); o.p(); C 2 o = new C 1 (); o.p(); C 1 +p() print C1 ถ าในคลาส C 2 ไม ม เมธอด p() และ superclass อ นก ไม ม เมธอดน 22
23 You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student()); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to: Object o = new Student(); // Implicit casting m(o); The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. public class PolymorphismDemo { public static void m(object x) { System.out.println(x.toString()); public static void main(string[] args) { m(new Student()); 23
24 Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Object o = new Student(); Student b = o;// A compilation error would occur. Why does the statement Object o = new Student() work and the statement Student b = o doesn t This is because a Student object is always an instance of Object, but an object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows: Object o = new Student(); Student b = (Student)o; // Explicit casting 24
25 Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Fruit fruit = new Fruit(); Apple x = (Apple)fruit; //no Orange x2 = (Orange)fruit;//no //runtime error, ClassCastException Apple apple = new Apple (); Fruit x = apple; //ok Fruit x2 =(Fruit)apple;//ok Fruit fruit = new Apple(); Apple x = (Apple)fruit; Orange x2 = (Orange)fruit;//no //runtime error, ClassCastException Apple +p() +m() fruit.m(); x.m(); Fruit +p() Orange +p() +m() 25
26 Use the instanceof operator to test whether an object is an instance of a class: Fruit myobject = new Apple();... // Some lines of code /** Perform casting if myobject is an instance of Apple */ if (myobject instanceof Apple) { Apple obj = (Apple)myObject; System.out.println( call m: + obj.m());... Fruit +p() Apple +p() +m() Orange +p() +m() 26
27 GeometricObject -color: String -filled: boolean -datecreated: java.util.date +GeometricObject() +getcolor(): String +setcolor(color: String): void +isfilled(): boolean +setfilled(filled: boolean): void +tostring(): String +getarea():double The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns a string representation of this object. public class Rectangle extends GeometricObject{... public Rectangle(double width, double height) { this.width = width; this.height = height; public double getarea() { return width * height; Circle -radius: double +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getarea(): double +getperimeter(): double +getdiameter(): double Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +getwidth(): double +setwidth(width: double): void +getheight(): double +setheight(height: double): void +getarea(): double +getperimeter(): double public class Circle extends GeometricObjet{... public Circle(double radius) { this.radius = radius; public double getarea() { return radius * radius * Math.PI; 27
28 1. public class TestCircleRectangle { 2. public static void main(string[] args) { 3. double totalarea =0; 4. GeometricObject obj[] = {new Circle(5),new Rectangle(6,7); 5. for (int i = 0; i < obj.length; i++) { 6. System.out.println( area of obj[ + i + ] is : +obj[i].getarea()); 7. totalarea = totalarea+obj[i].getarea(); System.out.println( totalarea : + totalarea); area of obj[0] is : area of obj[1] is :42.0 totalarea : ถ าจะเร ยก getradius() จาก object ของคลาส Circle ต องท าอย างไร if(obj[i] instanceof Circle){ Circle tmp =(Circle)obj[i]; tmp.getradius(); //((Circle)obj[i]).getRadius(); 28
29 The protected modifier can be applied on data fields and methods in a class. A protected data field or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. private, default, protected, public Visibility increases private, none (if no modifier is used), protected, public 29
30 package p1; 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(); package p2; public class C3 extends C1 { can access x; can access y; can access z; cannot access u; public class C4 extends 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(); import p1.*; 30
31 Modifier on members in a class Accessed from the same class Accessed from the same package Accessed from a subclass Accessed from a different package public protected - default - - private
32 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. 32
33 The final variable is a constant: final static double PI = ; The final class cannot be extended: final class Math {... The final instance method cannot be overridden by its subclasses. final void method(){ final class A{ class B extends A{ //compile error class A{ final void m(){ class B extends A{{ void m() { //compile error 33
34 You can override an instance method, but you cannot override a data field (instance or static) or a static method. If you declare a data field or a static method in a subclass with the same name as one in the superclass, the one in the superclass is hidden(กรณ เร ยกใน subclass), but it still exists. The two data fields or static methods are independent. You can reference the hidden field or static method using the super keyword in the subclass. The hidden field or method can also be accessed via a reference variable of the superclass s type. 34
35 When accessing a data field or a static method, the declared type of the reference variable decides which method is used at compilation time. (static binding) A obj = new B(); When invoking an instance method from a reference variable, the actual class of the object referenced by the variable decides which implementation of the method is used at runtime. (dynamic binding) A obj = new B(); 35
36 public class A { public int i = 1; public static int j = 11; public static String m1() {return "A's static m1"; public String m2() { return "A's instance m2"; public String m3() {return "A's instance m3"; public class B extends A { public int i = 2; public static int j = 12; (1) x.i is 1 (2) (B)x.i is 2 (3) x.j is 11 (4) ((B)x).j is 12 (5) x.m1() is A's static m1 (6) ((B)x).m1() is B's static m1 (7) x.m2() is B's instance m2 public static String m1(){return "B's static m1"; (8) x.m3() is A's instance m3 public String m2() {return "B's instance m2"; public class HidingDemo { public static void main(string[] args) { A x = new B(); // Access instance data field i System.out.println("(1) x.i is " + x.i); System.out.println("(2) (B)x.i is " + ((B)x).i); // Access static data field j System.out.println("(3) x.j is " + x.j); System.out.println("(4) ((B)x).j is " + ((B)x).j); // Invoke static method m1 System.out.println("(5) x.m1() is " + x.m1()); System.out.println("(6) ((B)x).m1() is " + ((B)x).m1()); // Invoke instance method m2 System.out.println("(7) x.m2() is " + x.m2()); System.out.println("(8) x.m3() is " + x.m3()); 36
37 Share common codes Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside a pair of braces. An initialization block appears within the class declaration, but not inside methods or constructors. It is executed as if it were placed at the beginning of every constructor in the class. public class Book { private static int numofobjects; private String title; private int id; public Book(String title) { numofobjects++; this.title = title; public Book(int id) { numofobjects++; this.id = id; Equivalent public class Book { private static int numofobjects; private String title; private int id; public Book(String title) { this.title = title; public Book(int id) { this.id = id; { numofobjects++; 37
38 A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded. The JVM loads a class when it is needed. A superclass is loaded before its subclasses. 38
39 class N { N() { System.out.println("(7) N's constructor body"); { System.out.println("(5) N's instance initialization block"); { System.out.println("(6) N's instance initialization block"); static { System.out.println("(2) N's static initialization block"); class M extends N { M() { System.out.println("(9) M's constructor body"); { System.out.println("(8) M's instance initialization block"); static { System.out.println("(3) M's static initialization block"); static { System.out.println("(4) M's static initialization block"); public class InitializationDemo { public static void main(string[] args) { M object = new M(); static { System.out.println("(1) InitializationDemo's static block"); 39
40 (1) InitializationDemo's static block (2) N's static initialization block (3) M's static initialization block (4) M's static initialization block (5) N's instance initialization block (6) N's instance initialization block (7) N's constructor body (8) M's instance initialization block (9) M's constructor body 40
41 You can create an array to store objects. But the array s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects. java.util.arraylist +ArrayList() +add(o: Object) : void +add(index: int, o: Object) : void +clear(): void +contains(o: Object): boolean +get(index: int) : Object +indexof(o: Object) : int +isempty(): boolean +lastindexof(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : Object +set(index: int, o: Object) : Object Creates an empty list. Appends a new element o at the end of this list. Adds a new element o at the specified index in this list. Removes all the elements from this list. Returns true if this list contains the element o. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns true if this list contains no elements. Returns the index of the last matching element in this list. Removes the element o from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index. 41
Chapter 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 informationChapter 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationIST311. Advanced Issues in OOP: Inheritance and Polymorphism
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
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 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 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 informationWe are on the GUI fast track path
We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter
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 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 informationCS171:Introduction to Computer Science II. Li Xiong
CS171:Introduction to Computer Science II Simple Sorting (cont.) + Interface Li Xiong Today Simple sorting algorithms (cont.) Bubble sort Selection sort Insertion sort Interface Sorting problem Two useful
More informationChapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9
Chapter 6 Arrays Chapter 8 Strings Chapter 7 Objects and Classes Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter
More informationIntroduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017
Introduction Programming Using Python Lecture 8 Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017 Chapter 12 Inheritance and Class Design Review Suppose you will define classes to model circles, rectangles, and
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 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 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 informationEKT472: Object Oriented Programming. Overloading and Overriding Method
EKT472: Object Oriented Programming Overloading and Overriding Method 2 Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name When a method
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 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 informationInheritance. 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 informationJava Classes, Objects, Inheritance, Abstract and Interfaces Recap
Java Classes, Objects, Inheritance, Abstract and Interfaces Recap CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 1 Objectives To recap classes, objects,
More informationChapter 8 Objects and Classes
Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java
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 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 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java
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 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 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 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 informationOO Programming Concepts
Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java
More informationOutline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.
Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not
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 informationMore 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 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 informationDay 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 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 informationChapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University
Chapter 9 Objects and Classes CS1: Java Programming Colorado State University Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops,
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 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 informationChapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
Chapter 9 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java
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 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 informationQuestions 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 informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
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 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 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 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 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 informationCOP 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 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 informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
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 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 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 informationInheritance. 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 informationUFCE3T-15-M Object-oriented Design and Programming
UFCE3T-15-M Object-oriented Design and Programming Block1: Objects and Classes Jin Sa 27-Sep-05 UFCE3T-15-M Programming part 1 Objectives To understand objects and classes and use classes to model objects.
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 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 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 informationAP CS Unit 6: Inheritance Notes
AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything
More informationGenerics. CSE260, Computer Science B: Honors Stony Brook University
Generics CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 1 2 Objectives To know the benefits of generics. To use generic classes and interfaces. To declare
More informationInheritance, 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 informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationObject Oriented Programming
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 11 Object Oriented Programming Eng. Mohammed Alokshiya December 16, 2014 Object-oriented
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 informationJava: introduction to object-oriented features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationObject Orientated Programming Details COMP360
Object Orientated Programming Details COMP360 The ancestor of every action is a thought. Ralph Waldo Emerson Three Pillars of OO Programming Inheritance Encapsulation Polymorphism Inheritance Inheritance
More informationImplements 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 informationOBJECT 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 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 informationLecture 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 informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
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 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 informationCISC370: Inheritance
CISC370: Inheritance Sara Sprenkle 1 Questions? Review Assignment 0 due Submissions CPM Accounts Sara Sprenkle - CISC370 2 1 Quiz! Sara Sprenkle - CISC370 3 Inheritance Build new classes based on existing
More informationCLASS DESIGN. Objectives MODULE 4
MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors
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 informationC12a: The Object Superclass and Selected Methods
CISC 3115 TY3 C12a: The Object Superclass and Selected Methods Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/4/2018 CUNY Brooklyn College 1 Outline The Object class and
More informationProgramming in Java, 2e Sachin Malhotra Saurabh Choudhary
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism
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 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 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 information