Rules and syntax for inheritance. The boring stuff

Similar documents
Everything is an object. Almost, but all objects are of type Object!

Java Magistère BFA

Practice for Chapter 11

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

INHERITANCE. Spring 2019

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.

What is Inheritance?

First IS-A Relationship: Inheritance

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

Inheritance and Polymorphism

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

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

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

CS 251 Intermediate Programming Inheritance

AP CS Unit 6: Inheritance Notes

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

1 Shyam sir JAVA Notes

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

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

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

Operators and Expressions

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Inheritance (Part 5) Odds and ends

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

CS-202 Introduction to Object Oriented Programming

More on Objects in JAVA TM

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

CS/ENGRD 2110 SPRING 2018

Introduction to Inheritance

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

Lecture 4: Extending Classes. Concept

Inheritance (continued) Inheritance

More Relationships Between Classes

Java Object Oriented Design. CSC207 Fall 2014

Logistics. Final Exam on Friday at 3pm in CHEM 102

Inheritance. Transitivity

Self-review Questions

Declarations and Access Control SCJP tips

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Abstract Classes and Interfaces

Binghamton University. CS-140 Fall Dynamic Types

Java: introduction to object-oriented features

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

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Making New instances of Classes

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CSE 401/M501 Compilers

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Polymorphism. return a.doublevalue() + b.doublevalue();

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

CISC370: Inheritance

Inheritance and Polymorphism. CS180 Fall 2007

CLASS DESIGN. Objectives MODULE 4

25. Generic Programming

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

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

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

COP 3330 Final Exam Review

C++ Important Questions with Answers

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

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

CS18000: Problem Solving And Object-Oriented Programming

Object-Oriented Programming More Inheritance

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Inheritance and Polymorphism in Java

Class, Variable, Constructor, Object, Method Questions

Overriding methods. Changing what we have inherited from e.g. Object

The class Object. Lecture CS1122 Summer 2008

Handout 9 OO Inheritance.

Example: Count of Points

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

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

Inheritance (Outsource: )

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

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

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS61B Lecture #13: Packages, Access, Etc.

CS 61B Discussion 5: Inheritance II Fall 2014

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

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

Subclasses, Superclasses, and Inheritance

Java Fundamentals (II)

Object Oriented Programming. Java-Lecture 11 Polymorphism

Inheritance (Part 2) Notes Chapter 6

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Equality for Abstract Data Types

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CPS 506 Comparative Programming Languages. Programming Language

OBJECT ORİENTATİON ENCAPSULATİON

Transcription:

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 you as the first instruction of your constructor. If you want to call a constructor of the superclass explicitly, it must be done as the first instruction of the constructor. The implicit call is of course to the no-arguments-constructor of the superclass, so if your superclass lacks such a constructor, you must call one of the existing constructors yourself, or you will have a compiler error. Do not add a no-arguments-constructor just to fix this problem!

You can only extend one class (at the time) Java uses a single-rooted hierarchy for inheritance, which means that you can only extend one class directly. There is another construct for achieving something similar to declaring a class as a subtype to many types, which is called interfaces. We ll look at interfaces in a later chapter.

You can prevent your class from being extended If you want to say that your class cannot be (and should not be) extended, you can use the keyword final at the class declaration: public final class String /*this class cannot be extended*/ Unless you have a very good reason to let people extend your classes, we recommend that you use the final keyword to prevent inheritance. The reason is that it is very complicated to design a class meant for inheritance and avoid the pitfalls which follow with inheritance.

Another way to prevent your class from extension You can also make all constructors private in order to prevent people from extending your class. Instead of public constructors, you can write public static methods which create and return new instances of your class. Such methods are often called factories. public class Runtime { private static Runtime currentruntime = new Runtime(); public static Runtime getruntime() { return currentruntime; private Runtime() { // no one can make an instance (or inherit)...

Sometimes you want to keep some methods To prevent a single method from being overridden (re-defined) in a subclass, you can also use the final keyword. A final method cannot be overridden. Methods called from the constructor must be final, because if they are overridden, they will be called before the subclass has been instantiated.

Non-final method call FAIL public class Super{ public Super(){ method();// uh-oh public void method(){ class Sub extends Super{ private String s; public Sub(){ s="abc"; // too late! @Override public void method(){ s=s.touppercase(); public class TestSub{ public static void main(string[] args){ Sub sub = new Sub(); $ java TestSub Exception in thread "main" java.lang.nullpointerexception at Sub.method(Super.java:21) at Super.<init>(Super.java:4) at Sub.<init>(Super.java:16) at TestSub.main(Super.java:11)

What just happened? class Sub extends Super{ private String s; public Sub(){ s="abc"; // too late! @Override public void method(){ s=s.touppercase(); public class Super{ public Super(){ method();// uh-oh public void method(){ Before s is initialized, an implicit call to super() is done. In the constructor of the super class we have: method(); But method is overriden, so the overridden version is called. S is still null!

Checking class type at runtime The instanceof operator checks class affiliation. It checks if the left hand operand is an instance of the right hand operand or any of its subclasses. Special case: null is not an instance of anything. String s = ""; Object o = new Object(); if(s instanceof Object){ // true, String extends Object if(o instanceof String){ // false

Getting the actual class You can use the getclass() method inherited from Object, in order to get a handle to the actual class of an object. Object o = new String(); System.out.println("o.getClass().getName(): " + o.getclass().getname()); // java.lang.string will be printed

CC-BY City of Vancouver Archives - https://www.flickr.com/photos/vancouver-archives/8229393567

Anonymous class You can create an extending class on the fly like this: public class Anonymous{ public static void main(string[] args){ System.out.println( new Object(){ public String tostring(){ return "I am an object"; ); // Will extend Object and override tostring(). // Will print I am an object

Collections of a Superclass It is possible to create a collection object, like a list, with references to a supertype. While this is convenient, it is also pretty dangerous as we will show. Let s assume we have an array of Object references. We know that each object reference in the array can refer to an object of any class type, since everything is an object (every class can be viewed as also being of type Object). This might sound like a good idea first, since we don t have to worry about whether we can assign the references in the array to some object - it will always work!

Collections of a Superclass Object[] objs = new Object[4]; objs[0] = new String("ABC"); objs[1] = new Integer(4); objs[2] = new Customer(); objs[3] = new Passport(); // Legal, since all classes are subtypes to Object

Collections of a Superclass Object[] objs = new Object[4]; objs[0] = new String("ABC"); objs[1] = new Integer(4); objs[2] = new Customer(); objs[3] = new Passport(); But is it good? The compiler and runtime let us put anything in the array. This is often not what we want. Imagine if we have an array presumably holding references to a list of, say, Customer objects. If we declare that array as above (of type array of Object references), nothing is preventing us or anyone else from populating the array with references to something else...

ArrayList example - First atempt We could use an ArrayList instead for our customers: ArrayList customers = new ArrayList(); But as soon as we add a reference to e.g. a Customer to the list, we ll get a warning from the compiler: Note: SomeClass.java uses unchecked or unsafe operations. The reason is that an ArrayList created as above can hold any type of references, just like the array of Object references before, which is not safe.

ArrayList example - First atempt - failure Created like below, the list could hold references to any class. ArrayList customers = new ArrayList(); So nothing is preventing us from also adding a String to the list, together with some Customer references. When we get a reference from the list, like this: customers.get(0); we will actually get the reference as of type Object. So we d need to cast it to a Customer if that s what we want. But if it s really a String, that cast would fail: Exception in thread "main" java.lang.classcastexception: java.lang.string cannot be cast to Customer

ArrayList example - Limiting type to Customer Rather, we should declare the ArrayList as only accepting Customer references: ArrayList<Customer> customers = new ArrayList<>(); That syntax uses a concept called generics. You may think of it as a typesafe ArrayList (or any collection class) which in the example above creates an ArrayList which will only accept references to Customers. Not only that, when getting a reference from the ArrayList, it will automatically be of the correct type (Customer), whereas the bad ArrayList would only return references as Object references (which we would need to cast).