Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses

Similar documents
Chapter 12: Inheritance

CIS 110: Introduction to computer programming

Inheritance and Polymorphism

ITI Introduction to Computing II

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

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

ITI Introduction to Computing II

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

Chapter 5. Inheritance

CLASS DESIGN. Objectives MODULE 4

Overriding Variables: Shadowing

Week 11: Class Design

Chapter 7. Inheritance

Example: Count of Points

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

Java Fundamentals (II)

Practice for Chapter 11

INHERITANCE. Spring 2019

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

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

Exam Duration: 2hrs and 30min Software Design

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

More about inheritance

CMSC 132: Object-Oriented Programming II. Inheritance

Java Simple Data Types

Exercise: Singleton 1

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

SSE3052: Embedded Systems Practice

The class Object. Lecture CS1122 Summer 2008

Class, Variable, Constructor, Object, Method Questions

Instance Members and Static Members

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Inheritance (Part 5) Odds and ends

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

JAVA MOCK TEST JAVA MOCK TEST II

Programming overview

Inheritance: Definition

Implements vs. Extends When Defining a Class

Java Object Oriented Design. CSC207 Fall 2014

Lecture 18 CSE11 Fall 2013 Inheritance

Definition of DJ (Diminished Java)

Lab05: Inheritance and polymorphism

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

Java Magistère BFA

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

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

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

Chapter 5 Object-Oriented Programming

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Create a Java project named week9

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

C++ Important Questions with Answers

First IS-A Relationship: Inheritance

What is Inheritance?

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Key Java Simple Data Types

Java Simple Data Types

Inheritance. Chapter 7. Chapter 7 1

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

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

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

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CS1150 Principles of Computer Science Objects and Classes

CS313D: ADVANCED PROGRAMMING LANGUAGE

Programming Languages and Techniques (CIS120)

JAVA OBJECT-ORIENTED PROGRAMMING

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

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

Inheritance, Polymorphism, and Interfaces

Programming II (CS300)

CS260 Intro to Java & Android 03.Java Language Basics

coe318 Lab 2 ComplexNumber objects

PROGRAMMING LANGUAGE 2

Programming Languages and Techniques (CIS120)

CH. 2 OBJECT-ORIENTED PROGRAMMING

Methods Common to all Classes

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

INHERITANCE AND EXTENDING CLASSES

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

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

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

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

Lecture 3. Lecture

Inheritance (Part 2) Notes Chapter 6

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

EECS 1001 and EECS 1030M, lab 01 conflict

Midterm 2 Grading Key

ITI Introduction to Computing II

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS Programming I: Inheritance

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Transcription:

Objectives Inheritance Students should: Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create new Java classes. Understand the mechanism involved in instance creation of a class inherited from another class. Understand the mechanism involved in method invocation from a class inherited from another class. 2 Creating Subclasses from Superclasses Creating Subclasses from Superclasses Inheritance is an ability to derive a new class from an existing class. The new class is said to be a subclass, or derived class, of the class it is derived from, which is called superclass, or base class. A subclass can be thought of as an extension of its superclass. It inherits all attributes and behaviors from its superclass. More attributes and behaviors can be added to existing ones of its superclass. Inheritance is an ability to derive a new class from an existing class. A B Additional attributes and behaviors superclass / base class subclass / derived class 3 4

Creating subclasses Creating subclasses Suppose that we have a class called L12A public class L12A public int x; public double d; public double f() return x*d; To create a new class L12B that inherits all attributes and behaviors from L12A, We use the keyword extends to let Java know that L12B inherits from L12A. possible additional attributes/behaviors could be listed in here. public class L12B extends L12A 5 The following program that makes use of L12B. public class InheritanceDemo0 L12B b = new L12B(); b.x = 2; b.d = 1.5; System.out.println("b.f() = "+b.f()); 6 Creating subclasses Creating subclasses Creating a new class contains all attributes and behaviors of its superclass together with some additional attributes and behaviors. public class L12C extends L12A public String name; public String tostring() return name+":"+x+","+d; 7 8

Example of creating subclasses consider the following program and observe its output. The superclass public class InheritanceDemo01 L12C c = new L12C(); c.x = 5; c.d = 2.0; c.name = "An object with a name"; System.out.println("c.f() = "+c.f()); System.out.println("c.name = "+c.name); System.out.println(c); 9 10 The subclass public class CUStudent private String id; private String firstname, lastname; private double gpa; private CUStaff academicadvisor; public CUStudent(String id, String firstname, String lastname) this.id = id; this.firstname = firstname; this.lastname = lastname; gpa = 0.0; academicadvisor = null; public String getid() return id; public String getfullname() return firstname+" "+lastname; // continue on the next page 11 12

public double getgpa() return gpa; public void updategpa(double gpa) this.gpa = gpa; public void showinfo() System.out.println(); System.out.println("ID:"+getId()); System.out.println(getFullName()); System.out.println("Advisor:"+getAdvisor()); public void assignadvisor(custaff a) academicadvisor = a; public CUStaff getadvisor() return academicadvisor; public String tostring() return "CUStudent:"+getFullName(); 13 public class EngStudent extends CUStudent private department; public EngStudent(String id,string firstname,string lastname) super(id,firstname,lastname); department = null; public String getdepartment() return department; public boolean setdepartment(string dept) if(validdepartment(dept)) department = dept; return true; else return false; private boolean validdepartment(string dept) // This method returns true if the input String is a valid department // in Engineering school. : 14 Designing Class Inheritance Hierarchy Let s look at the following example to see EngStudent in action. public class InheritanceDemo1 EngStudent a = new EngStudent("4971234521","Alan","Smith"); CUStaff b = new CUStaff("3600","Alex","Ferguson"); a.assignadvisor(b); a.showinfo(); if(a.setdepartment("ice")) System.out.println(a.getDepartment()); A good class hierarchy helps us understand the relationship among classes. Superclasses are always more general than subclasses since a subclass possesses everything that its superclass has while it can also possess additional attributes and behaviors. There is an is-a relationship between a subclass and its superclass. 15 16

Example of a hierarchy among some quadrilaterals. Access Control Class access rights regarding to three access levels used in Java: public, private, and protected. When no explicit access levels are used, the access rights are the ones listed in the row labeled default. : the corresponding accessing class can access resources with the corresponding access level 17 18 Access Control Access Control public class MyDot2D private double x=0; private double y=0; public double getx() return x; public double gety() return y; public class AccessLevelDemo1 MyDot2D p = new MyDot2D(); System.out.println(p.x); System.out.println(p.y); Compile: compilation errors since x and y have private access level and attempts to access them directly using the dot operator AccessLevelDemo1.Java:6: x has private access in MyDot2D System.out.println(p.x); AccessLevelDemo1.Java:7: y has private access in MyDot2D System.out.println(p.y); 19 20

Keyword super public class MySuperclass public int a = 1; public int b = 2; public void f() System.out.println("\tf() of MySuperclass is called."); public void g() System.out.println("\tg() of MySuperclass is called."); 21 Keyword super public class MySubclass extends MySuperclass public int a = 9; public void f() System.out.println("\tf() of MySubclass is called."); public void test() System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("super.a = "+super.a); System.out.println("super.b = "+super.b); System.out.println("f()"); f(); System.out.println("g()"); g(); System.out.println("super.f()"); super.f(); System.out.println("super.g()"); super.g(); 22 Keyword super Object Variables public class SuperDemo MySubclass y = new MySubclass(); y.test(); A variable whose type is a class can refer to an object of that class as well as an object of any one of its subclasses. A variable of a class cannot be used to refer to an object of its superclass, just like when a variable cannot be used to refer an object whose class is different from the variable type. 23 24

Object Variables Object Variables Recall the class hierarchy of L12A, L12B and L12C. Each of the following code segments are valid and compiled without errors. L12A a = new L12A(); L12B b = new L12B(); L12C c = new L12C(); a = b; a = c; L12A a1 = new L12B(); L12A a2 = new L12C(); L12A [] a = new L12A[3]; a[0] = new L12A(); a[1] = new L12B(); a[3] = new L12C(); 25 1 2 3 4 5 6 7 8 9 10 11 12 However, the following program cannot be compiled successfully. public class ObjectVariableInvalidDemo L12A a = new L12A(); L12B b = new L12B(); L12C c = new L12C(); b = a; c = a; b = c; Incompatible types 26 Method Overriding and Polymorphism When a method that has already been defined in a class is redefined in its subclass using the same identifier and the same list of input arguments, it is called that the method defined in the subclass overrides the one in its superclass. When this happens, which method to be invoked, i.e. the one in the superclass or the one in the subclass, depends on the type of the object from which the method is invoked. 27 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Method Overriding and Polymorphism public class MethodOverridingDemo1 L12A a = new L12A(); a.x = 2; a.d = 1.0; L12D d = new L12D(); d.x = 2; d.d = 1.0; d.y = 2.5; System.out.println("a.f()="+a.f()); System.out.println("d.f()="+d.f()); a = d; System.out.println("a.f()="+a.f()); 28

Instance Creation Mechanism When an instance or object of a class is created, if there is no explicit call of any constructors of its superclass, the no-argument constructor of the superclass is called automatically before the execution of any statements in the subclass s constructor (if there are any). Instance Creation Mechanism public class L12E public L12E() System.out.println("\tL12E() is called."); public class L12F extends L12E 29 30 Instance Creation Mechanism Instance Creation Mechanism public class L12G extends L12E public L12G() System.out.println("\tL12G is called."); public L12G(String s) System.out.println("\tL12G(String s) is called."); public L12G(int i) super(); System.out.println("\tL12G(int i) is called."); L12F and L12G are subclasses of L12E. Let s consider the following program. Pay attention to messages printed on screen when each object is created. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class CreationDemo1 System.out.println("1)-----------------"); L12F f = new L12F(); System.out.println("2)-----------------"); L12G g1 = new L12G(); System.out.println("3)-----------------"); L12G g2 = new L12G("Hello"); System.out.println("4)-----------------"); L12G g3 = new L12G(8); 31 32

Instance Creation Mechanism Keep in mind that the super() statement has to be used in the first statement only. Otherwise, the class will not be compiled successfully. public class L12H extends L12E public L12H() System.out.println("\tL12H is called."); super(); 33