Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“

Slides:



Advertisements
Similar presentations
CS 211 Inheritance AAA.
Advertisements

Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
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.
Java Class and Inheritance.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 21: Sorting, cont.
Introduction to Data Structures, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Object Oriented Programming Concepts.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Inheritance and Polymorphism
1 Topic 10 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.”
Chapter 10 Classes Continued
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
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.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
1 Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Inheritance, Polymorphism, and Interfaces 1 What’s past is prologue. Don’t write it twice — write it once and reuse it. Advanced Placement Computer Science.
1 More About Derived Classes and Inheritance Chapter 9.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Classes and Inheritance
Chapter 11 Inheritance and Polymorphism
Final and Abstract Classes
Inheritance and Polymorphism
03/10/14 Inheritance-2.
Interfaces I once attended a Java user group meeting where James Gosling (Java's inventor) was the featured speaker. During the memorable Q&A session,
Advanced Programming in Java
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Modern Programming Tools And Techniques-I Inheritance
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Chapter 9 Inheritance and Polymorphism
Inheritance Chapter 5.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Extending Classes.
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
Polymorphism.
Advanced Programming Behnam Hatami Fall 2017.
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Java – Inheritance.
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Overriding Methods & Class Hierarchies
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Fundaments of Game Design
Lecture 6 Inheritance CSE /26/2018.
Advanced Placement Computer Science
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
CS 200 More Classes Jim Williams, PhD.
Chapter 8 Inheritance Part 2.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Polymorphism.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“

Features of OO Programming Encapsulation abstraction information hiding breaking problem up based on data types Inheritance code reuse specialization "New code using old code." CS 314 Inheritance

Encapsulation Create a program to allow people to play the game Monopoly Create classes for money, dice, players, the bank, the board, chance cards, community chest cards, pieces, etc. Some classes use other classes: the board consists of spaces a player has money a piece has a position also referred to as composition CS 314 Inheritance

Inheritance Another kind of relationship exists between data types There are properties in Monopoly a street is a kind of property a railroad is a kind of property a utility is a kind of property CS 314 Inheritance

Inheritance In Monopoly there is the concept of a Property All properties have some common traits they have a name they have a position on the board they can be owned by players they have a price to buy But some things are different for each of the three kinds of property How to determine rent when another player lands on the Property CS 314 Inheritance

What to Do? If we have a separate class for Street, Railroad, and Utility there is going to be a lot of code copied hard to maintain an anti-pattern Inheritance is a programming feature to allow data types to build on pre-existing data types without repeating code CS 314 Inheritance

Inheritance in Java Java is designed to encourage object oriented programming all classes, except one, must inherit from exactly one other class The Object class is the cosmic super class The Object class does not inherit from any other class The Object class has several important methods: toString, equals, hashCode, clone, getClass implications: all classes are descendants of Object all classes and thus all objects have a toString, equals, hashCode, clone, and getClass method toString, equals, hashCode, clone normally overridden CS 314 Inheritance

Nomenclature of Inheritance In Java the extends keyword is used in the class header to specify which preexisting class a new class is inheriting from public class Student extends Person Person is said to be the parent class of Student the super class of Student the base class of Student an ancestor of Student Student is said to be a child class of Person a sub class of Person a derived class of Person a descendant of Person CS 314 Inheritance

Clicker Question 1 What is the primary reason for using inheritance when programming? A. To make a program more complicated B. To copy and paste code between classes C. To reuse pre-existing code D. To hide implementation details of a class E. To ensure pre conditions of methods are met. CS 314 Inheritance

Clicker Question 2 What is output when the main method is run? public class Foo { public static void main(String[] args) { Foo f1 = new Foo(); System.out.println(f1.toString()); } } A. 0 B. null C. Unknown until code is actually run. D. No output due to a syntax error. E. No output due to a runtime error. CS 314 Inheritance

Simple Code Example Create a class named Shape what class does Shape inherit from what methods can we call on Shape objects? add instance variables for a position override the toString method Create a Circle class that extends Shape add instance variable for radius debug and look at contents try to access instance var from Shape constructor calls use of key word super CS 314 Inheritance

Overriding methods any method that is not final may be overridden by a descendant class same signature as method in ancestor may not reduce visibility may use the original method if simply want to add more behavior to existing CS 314 Inheritance

Constructors Constructors handle initialization of objects When creating an object with one or more ancestors (every type except Object) a chain of constructor calls takes place The reserved word super may be used in a constructor to call a one of the parent's constructors must be first line of constructor if no parent constructor is explicitly called the default, 0 parameter constructor of the parent is called if no default constructor exists a syntax error results If a parent constructor is called another constructor in the same class may no be called no super();this(); allowed. One or the other, not both good place for an initialization method CS 314 Inheritance

The Keyword super super is used to access something (any protected or public field or method) from the super class that has been overridden Rectangle's toString makes use of the toString in ClosedShape my calling super.toString() without the super calling toString would result in infinite recursive calls Java does not allow nested supers super.super.toString() results in a syntax error even though technically this refers to a valid method, Object's toString Rectangle partially overrides ClosedShapes toString CS 314 Inheritance

Creating a SortedIntList

A New Class Assume we want to have a list of ints, but that the ints must always be maintained in ascending order [-7, 12, 37, 212, 212, 313, 313, 500] sortedList.get(0) returns the min sortedList.get( list.size() – 1 ) returns the max CS 314 Inheritance

Implementing SortedIntList Do we have to write a whole new class? Assume we have an IntList class. Which of the following methods would have to be changed? add(int value) int get(int location) String toString() int size() int remove(int location) CS 314 Inheritance

Overriding the add Method First attempt Problem? solving with insert method double edged sort solving with protected What protected really means CS 314 Inheritance

Problems What about this method? void insert(int location, int val) void insertAll(int location, IntList otherList) SortedIntList is not a good application of inheritance given the IntList we developed CS 314 Inheritance

ClosedShape and Rectangle classes More Example Code ClosedShape and Rectangle classes CS 314 Inheritance

Shape Classes Declare a class called ClosedShape assume all shapes have x and y coordinates override Object's version of toString Possible sub classes of ClosedShape Rectangle Circle Ellipse Square Possible hierarchy ClosedShape <- Rectangle <- Square CS 314 Inheritance

A ClosedShape class public class ClosedShape { private double myX; private double myY; public ClosedShape() { this(0,0); } public ClosedShape (double x, double y) { myX = x; myY = y; } public String toString() { return "x: " + getX() + " y: " + getY(); } public double getX(){ return myX; } public double getY(){ return myY; } // Other methods not shown CS 314 Inheritance

A Rectangle Constructor public class Rectangle extends ClosedShape { private double myWidth; private double myHeight; public Rectangle( double x, double y, double width, double height ) { super(x,y); // calls the 2 double constructor in // ClosedShape myWidth = width; myHeight = height; } // other methods not shown CS 314 Inheritance

A Rectangle Class public class Rectangle extends ClosedShape { private double myWidth; private double myHeight; public Rectangle() { this(0, 0); } public Rectangle(double width, double height) { myWidth = width; myHeight = height; } public Rectangle(double x, double y, double width, double height) { super(x, y); myWidth = width; myHeight = height; } public String toString() { return super.toString() + " width " + myWidth + " height " + myHeight; CS 314 Inheritance

Initialization method public class Rectangle extends ClosedShape { private double myWidth; private double myHeight; public Rectangle() { init(0, 0); } public Rectangle(double width, double height) { init(width, height); public Rectangle(double x, double y, double width, double height) { super(x, y); init(width, height); private void init(double width, double height) { myWidth = width; myHeight = height; CS 314 Inheritance

Result of Inheritance Do any of these cause a syntax error? What is the output? Rectangle r = new Rectangle(1, 2, 3, 4); ClosedShape s = new CloseShape(2, 3); System.out.println( s.getX() ); System.out.println( s.getY() ); System.out.println( s.toString() ); System.out.println( r.getX() ); System.out.println( r.getY() ); System.out.println( r.toString() ); System.out.println( r.getWidth() ); CS 314 Inheritance

The Real Picture Fields from Object class Instance variables declared in Object Fields from ClosedShape class A Rectangle object Instance Variables declared in ClosedShape Available methods are all methods from Object, ClosedShape, and Rectangle Fields from Rectangle class Instance Variables declared in Rectangle CS 314 Inheritance

Access Modifiers and Inheritance public accessible to all classes private accessible only within that class. Hidden from all sub classes. protected accessible by classes within the same package and all descendant classes Instance variables should be private protected methods are used to allow descendant classes to modify instance variables in ways other classes can't CS 314 Inheritance

Why private Vars and not protected? In general it is good practice to make instance variables private hide them from your descendants if you think descendants will need to access them or modify them provide protected methods to do this Why? Consider the following example CS 314 Inheritance

Required update public class GamePiece { private Board myBoard; private Position myPos; // whenever my position changes I must // update the board so it knows about the change protected void alterPos( Position newPos ) { Position oldPos = myPos; myPos = newPos; myBoard.update( oldPos, myPos ); } CS 314 Inheritance