CS10092 : Inheritance in Java (#2 of 4) Gavin Brown

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
 In inheritance the child (subclass) chooses its parent (superclass)  Remember - only public or “protected” methods and variables are inherited  Should.
Improving structure with inheritance
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
1 Chapter 9a Abstract Classes & Dynamic Binding. 2 Abstract Classes All classes so far have been concrete classes –Classes that can be used to create.
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
OO terminology & objectives §Encapsulation l don’t touch my private data l get/set it using my public/package methods §Inheritance l a parent provides.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
November 27, 2001Lecture 231  Previous Lecture: Parameter passing Method overloading  Today’s Lecture: Introduction to inheritance Class diagrams and.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Inheritance ndex.html ndex.htmland “Java.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
Design issues for Object-Oriented Languages
Polymorphism in Methods
Web Design & Development Lecture 9
Lecture 12 Inheritance.
Inheritance and Polymorphism
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Topic 6 Generic Data Structures
More inheritance, Abstract Classes and Interfaces
CSE 143 Lecture 22 The Object class; Polymorphism read
Extending Classes.
CSE 143 Lecture 22 The Object class; Polymorphism read
CS18000: Problem Solving and Object-Oriented Programming
Polymorphism.
Advanced Inheritance Concepts
Chapter 14 Abstract Classes and Interfaces
Inheritance and Polymorphism
Interfaces.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Presentation transcript:

CS10092 : Inheritance in Java (#2 of 4) Gavin Brown

Porsche PorscheVersionTwo The class we have written has the header: public class PorscheVersionTwo extends Porsche This is now called a subclass of the Porsche class. The ‘extends Porsche’ part makes sure that Java recognises it as so. The Porsche class is said to be the superclass of the PorscheVersionTwo class. Super-class Sub-class REMINDER OF LAST TIME

public class PorscheVersionTwo extends Porsche { private double percentBoost; public void accelerate(int mph) { speed=speed+mph+(mph*percentBoost); } public void setTurboBoost( double perc ) { percentBoost = perc; } - The important bit is “extends Porsche” – that makes inheritance happen. - This class INHERITS all the methods/variables of the superclass. …as if they were copied down into the subclass, automatically. - The accelerate method here OVERRIDES the one from the superclass. - The setTurboBoost method ADDS EXTRA FUNCTIONALITY. REMINDER OF LAST TIME

public class Bicycle { private int numberOfGears; private int numberOfWheels; public void turn( double degrees ) { //code for turning corners } // more methods } public class MountainBike extends Bicycle { private double suspensionRatio; // more methods } REMINDER OF LAST TIME

Class Hierarchies REMINDER OF LAST TIME The subclasses inherit the ‘type’ of their superclass. Q. What type is MountainBike? This is called ‘polymorphism’. Bicycle RacingBikeMountainBike Porsche PorscheVersionTwo Vehicle

Today 1.Design – variables in the hierarchy? 2.More polymorphism – making use of it 3.Casting to subclasses 4.Checking the type of an object at runtime 5.Superclass… superconstructor 6.“abstract” classes

Design : Where do variables go? class Vehicle int numberOfWheels class Porsche extends Vehicle String numberPlate double currSpeed double nationalSpeedLimit class Bicycle extends Vehicle int numberOfGears class RacingBike extends Bicycle String sponsorName Bicycle RacingBike Porsche Vehicle Variables in COMMON go at the top of the hierarchy. Variables specific to a class go in that class. The same applies for methods.

Vehicle v1 = new Porsche(); Vehicle v2 = new Bicycle(); Vehicle v3 = new Plane(); System.out.println(v1.getNumberOfWheels()) System.out.println(v2.getNumberOfWheels()) System.out.println(v3.getNumberOfWheels()) Polymorphism (inheriting the ‘type’) makes this code possible : Making use of polymorphism > java test Let’s run that code:

Vehicle [] vehicleList = new Vehicle[4]; vehicleList[0] = new Porsche(); vehicleList[1] = new Bicycle(); vehicleList[2] = new Plane(); vehicleList[3] = new Porsche(); for (int i=0; i<4; i++) System.out.println(vehicleList[i].getNumberOfWheels()); Or even more useful, an array of Vehicle objects: Making use of polymorphism > java test Let’s run that code:

vehicleList[3] = new Porsche(); Vehicle v = vehicleList[3]; System.out.println( v.getNumberOfWheels() ); //ok System.out.println( v.getNumberPlate() ); //ERROR (because getNumberPlate() is part of the Porsche class, not the Vehicle class…) > javac test.java test.java:12: cannot resolve symbol symbol : method getNumberPlate() location: class Vehicle System.out.println( v.getNumberPlate() ); ^ 1 error Be careful with types…

Porsche p = (Porsche)vehicleList[3]; System.out.println( p.getNumberPlate() ); //ok! The object has to be cast to the subclass first: > javac test.java > java test > Be careful with types : casting to the subclass The word ‘Porsche’ in brackets tells Java which type we want to cast to.

Vehicle [] vehicleList = new Vehicle[4]; vehicleList[0] = new Porsche(); vehicleList[1] = new Bicycle(); vehicleList[2] = new Bicycle(); vehicleList[3] = new Porsche(); for (int i=0; i<4; i++) { System.out.print(“In your array position “+i+” is”); if (vehicleList[i] instanceof Porsche) { System.out.println(“ a fast car!”); } if (vehicleList[i] instanceof Bicycle) { System.out.println(“ my bike.”); } Checking the type of an object

> javac test.java > java test In your array position 0 is a fast car! In your array position 1 is my bike. In your array position 2 is my bike. In your array position 3 is a fast car! > Checking the type of an object

public class Porsche { private String numberPlate; public Porsche( String plate ) { numberPlate = plate; } … public class PorscheVersionTwo extends Porsche { public PorscheVersionTwo( String plate ) { super(plate); setNumberPlate(”$$ ” +numberPlate+ ” $$”); } … Superclass…superconstructor > java test

PorscheVersionTwo p2 = new PorscheVersionTwo(“cdc 9922”); System.out.println(p2.getNumberPlate()); public class PorscheVersionTwo extends Porsche { public PorscheVersionTwo( String plate ) { super(plate); setNumberPlate(”$$ ” +numberPlate+ ” $$”); } … Superclass…superconstructor > java test $$-cdc-9922-$$ Call to superconstructor MUST be first!

3 minutes…. How many wheels on a bike? Q. It makes sense to have a “Porsche” object, and also a “MountainBike” object. Does it make sense to have a “Vehicle” object?

Porsche p = new Porsche(); RacingBike rb = new RacingBike(); Vehicle v = new Vehicle(); // ???? Technically correct, but what does it mean? Bicycle RacingBikeMountainBike Porsche PorscheVersionTwo Vehicle

public abstract class Vehicle { private int numberOfWheels; public int getNumWheels() { return numberOfWheels; } public abstract void turn(); } And forces ALL subclasses to have a “turn()” method Provides data and methods common to all Vehicles Abstract class: Vehicle Abstract classes : Useful software engineering tool: when working in a team, write an abstract class and give it to a colleague to work from. You can provides some functionality, and impose some rules, like the above class making the rule that subclasses should have a turn() method.

public class Plane extends Vehicle { private double wingspan; public void takeOff() { // more code } Extending from the abstract Vehicle class > javac Plane.java Plane.java:1: Plane should be declared abstract; it does not define turn() in Vehicle public class Plane extends Vehicle ^ 1 error Here, the compiler is telling us that the Plane should be made abstract, because we do not define turn(). In fact, we should just define the turn() method and all will be fine. The compiler gave the best advice it could, assuming that we wanted Plane to be abstract, and forgot to do so.

Today 1.Design – variables in the hierarchy 2.More polymorphism – making use of it 3.Casting to subclasses 4.Checking object type: instanceof 5.Superclass… superconstructor 6.“Abstract” classes Next time 1.How to dynamically choose between methods at runtime 2.How inheritance can be used to hack a system and how to stop it 3.How Accenture built inheritance into the Sainsbury’s IT system