Classes and Inheritance Extending Classes, Chapter 5.2

Similar documents
OVERRIDING. 7/11/2015 Budditha Hettige 82

What is Inheritance?

CS-202 Introduction to Object Oriented Programming

Inheritance and Polymorphism

Polymorphism and Interfaces. CGS 3416 Spring 2018

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Practice for Chapter 11

Java Object Oriented Design. CSC207 Fall 2014

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

Binghamton University. CS-140 Fall Dynamic Types

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

Programming in C# Inheritance and Polymorphism

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Object-Oriented Programming (Java)

CS111: PROGRAMMING LANGUAGE II

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber


25. Generic Programming

Inheritance and Polymorphism

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

C10: Garbage Collection and Constructors

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

Chapter 14 Abstract Classes and Interfaces

CS Programming I: Inheritance

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

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Abstract class & Interface

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Inheritance (continued) Inheritance

ITI Introduction to Computing II

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

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

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.

Lecture 18 CSE11 Fall 2013 Inheritance

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

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

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

ITI Introduction to Computing II

Inheritance -- Introduction

Inheritance and object compatibility

More Relationships Between Classes

Exercise: Singleton 1

Super-Classes and sub-classes

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

Informatik II (D-ITET) Tutorial 6

Introduction to Object-Oriented Programming

First IS-A Relationship: Inheritance

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

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

CMSC 132: Object-Oriented Programming II. Inheritance

9/10/2018 Programming Data Structures Inheritance

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

ECE 122. Engineering Problem Solving with Java

Java Fundamentals (II)

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

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

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

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

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

CS260 Intro to Java & Android 03.Java Language Basics

CS 251 Intermediate Programming Inheritance

COMP 110/L Lecture 19. Kyle Dewey

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

Inheritance, Polymorphism, and Interfaces

C08: Inheritance and Polymorphism

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

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

INHERITANCE. Spring 2019

Inheritance Motivation

Object Orientated Programming Details COMP360

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

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

Object Oriented Programming: Based on slides from Skrien Chapter 2

Programming Language Concepts: Lecture 2

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

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Class, Variable, Constructor, Object, Method Questions

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

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

C11: Garbage Collection and Constructors

Example: Count of Points

CLASS DESIGN. Objectives MODULE 4

COP 3330 Final Exam Review

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

CS1150 Principles of Computer Science Objects and Classes

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Lecture 4: Extending Classes. Concept

Transcription:

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. Implements is used by classes that inherit from interfaces. Interfaces can never be extended by a class. Java allows only single inheritance for class extension but allows multiple extensions for interfaces. Example: public class NewClass extends BaseClass implements Interface1, Interface2,... InterfaceN... An interface can extend multiple interfaces: Example: public interface NewInterface extends Interface1, Interface2,..., InterfaceN... Extend When a class, called C2 extends C1, then C2 IS-A subclass of C1, and C1 is a superclass of C2. All public and proteted members of the superclass are accessible in the extended classes. Let s look at an example: public class Shape public class Rectangle extends Shape public class Circle extends Shape public class Square extends Rectangle Shape is the superclass of Rectangle and Circle Rectangle and Circle are subclasses of Shape Square is a subclass of both Rectangle and Shape public class Square extends Rectangle public static void main(string args[]) Shape shape = new Shape(); Rectangle rect = new Rectangle(); 1

Square square = new (); System.out.println(rect instanceof Shape); System.out.println(square instanceof Rectangle); System.out.println(square instanceof Shape); This would produce the following: true true true Constructors of Extended Classes To construct an extended class you need to initialize the fields inherited from the superclass and the fields declared in the extended class. We use the keyword super to call a super class constructor and method. Let s look at an example. public class ColoredPoint extends Point public Color color; //the Color class is part of java.awt.color class public ColoredPoint(final double x, final double y, final Color color) super(x,y);//this calls the construct for Point the Superclass // that matches the Point(double, double) constructor this.color = color;// provides the value for the color field of this class. : : : The super keyword must be the first statement of the subclass s constructor. This is the only way to invoke a superclass constructor. If no constructor is defined in the extended class, the no-arg constructor is provided by default. The default no-arg constructor simply invokes the noarg constructor of the superclass. For example, the following no-arg constructor will be provided implicitly for the Extended class when no constructor is provided explicitly. public class ExtendedClass extends SuperClass public ExtendedClass() super(); //methods and fields For the above example, the SuperClass must provide a no-arg constructor otherwise a compile error will result. To call a method of a superclass you do the following: super.method(); Subtypes and Polymorphism So what is a subtype? Our book defines subtype as: Type T1 is a subtype of T2 if every legitimate value of T1 is also a legitimate value of T2. In this case, T2 is a supertype of T1. Well, that is 2

clear as mud, so I looked this up from the Java Tutorials 1. It is possible to assign an object of one type to an object of another type as long as they are compatible. Lets look at an example Keep in mind that an Object is a supertype of Integer. Object someobject = new Object(); Integer someinteger = new Integer(10); someobject = someinteger; //this is acceptable Let s talk a little about polymorphism. In C, the rule of assignments is that the left-hand side and the right-hand side of an assignment must be of compatible types. In OOP we have polymorphic assignments, which means the type of expression at the right-hand side of an assignment must be a subtype of the type of the variable at the left-hand side of the assignment. Or as http: //www.tutorialspoint.com/java/java_polymorphism.htm tells us, polymorphism is the ability of an object to take on many forms. The most common of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. We can use the IS-A test to determine if polymorphism. Let s look at another example. //this example comes from the tutorialspoint.com site in footnote 1. public interface Vegetarian public class Animal public class Deer extends Animal implements Vegetarian /*The Deer class is polymorphic since it has multiple inheritance (extends and implements) * A Deer IS-A Animal * A Deer IS-A Vegetarian * A Deer IS-A Deer * A Deer IS-A Object * All of the above make the following legal */ Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; // As you would expect all the reference variable d, a, v, o" refer to the same Deer object in the heap. This next example shows how casting works. class Student... class Undergraduate extends Student... class Graduate extends Student... //two instances Student student1, student2; student1 = new Undergraduate(); //polymorphic assignment student2 = new Graduate(); // polymorphic assignment Graduate student3; student 3 = student2; //this will cause a compile error /*the right had side is a Student and the left hand side is a Graduate. Although student2 holds a reference to an instance of Graduate it is not a subtype of the left hand (student3). Casting is necessary because type checking is carried out at compile time and is based on the declared types of variables. */ 1 https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html 3

student3 = (Graduate) student2; //this will now compile Overriding Methods First lets discuss the difference between overriding a method and overloading a method. From our book, Overriding is concerned with methods of different classes that have an inheritance relationship. In overriding methods share the same name, signature, and return type. In contrast, overloading methods are part of the same class, but have different signatures. The book gives us an example the difference between overriding and overloading methods. However, the following webpage has the following example http://www.tutorialspoint.com/java/ java_polymorphism.htm /* File name : Employee.java */ public class Employee private String name; private String address; private int number; public Employee(String name, String address, int number) System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; public void mailcheck() System.out.println("Mailing a check to " + this.name + " " + this.address); public String tostring() return name + " " + address + " " + number; public String getname() return name; public String getaddress() return address; public void setaddress(string newaddress) address = newaddress; public int getnumber() return number; //Now suppose we extend Employee class as follows: /* File name : Salary.java */ public class Salary extends Employee private double salary; //Annual salary public Salary(String name, String address, int number, double 4

salary) super(name, address, number); setsalary(salary); public void mailcheck() System.out.println("Within mailcheck of Salary class "); System.out.println("Mailing check to " + getname() + " with salary " + salary); public double getsalary() return salary; public void setsalary(double newsalary) if(newsalary >= 0.0) salary = newsalary; public double computepay() System.out.println("Computing salary pay for " + getname()); return salary/52; /* File name : VirtualDemo.java */ public class VirtualDemo public static void main(string [] args) Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); System.out.println("Call mailcheck using Salary reference --"); s.mailcheck(); System.out.println("\n Call mailcheck using Employee reference--"); e.mailcheck(); The output is as follows: Constructing an Employee Constructing an Employee Call mailcheck using Salary reference -- Within mailcheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailcheck using Employee reference-- Within mailcheck of Salary class Mailing check to John Adams with salary 2400.0 Here is an explanation of the above output: 5

Here, we instantiate two Salary objects. one using a Salary reference s, and the other using an Employee reference e. While invoking s.mailcheck() the compiler sees mailcheck() in the Salary class at compile time, and the JVM invokes mailcheck() in the Salary class at run time. Invoking mailcheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailcheck(), the compiler sees the mailcheck() method in the Employee class. Here, at compile time, the compiler used mailcheck() in Employee to validate this statement. At run time, however, the JVM invokes mailcheck() in the Salary class. This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time. Just a few more thoughts before I rap this section up. Final: a method declared final cannot be overridden in a subclass. Final methods are useful in preventing accidental overriding of subclass methods. Also, final methods also allow the java compiler and JVM to optimize byte-code. Invoking Overridden Methods: The keyword super should be used to invoke an overridden method. The super keyword represents the superclass. 6