Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
OOP: Inheritance By: Lamiaa Said.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Inheritance Inheritance Reserved word protected Reserved word super
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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,
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
Java Class and Inheritance.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 21: Sorting, cont.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
“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 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 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.
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Classes and Inheritance
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Chapter 14 Abstract Classes and Interfaces
Advanced Placement Computer Science
Presentation transcript:

Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract classes and interface

l class Circle { public static final double PI = ; public double x, y, r; l } l public class example{ public static void main(String[] args){ Circle.PI = 4; } l } §Is this correct?

class variable l class Circle { public static final double PI = ; public double x, y, r; l } l public class example{ public static void main(String[] args){ Circle.PI = 4;//Error } l } §The final keyword means that this variable can never be changed.

public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) return c; else return this; } //other methods omitted here. } §Is this correct?

class method public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) //Error return c; else return this;//Error } §static methods may not manipulate any instance variables!

Method Overloading and Overriding §What is the difference?

Overloading and Overriding §What is the difference? §Overloading l several methods of the same name can be defined, as long as the methods have different sets of parameters §Overriding l a subclass can redefine a superclass method by using the same signature

Overloading public class Overload { // first definition of method square public int square(double x){ return x * x; } // second definition of method square public double square(double y){ return y * y; } } //end class Overload §Is this correct?

Overloading public class Overload { // first definition of method square with double argument public int square(double x){ return x * x; } // second definition of method square with double argument // causes syntax error public double square(double y){ return y * y; } } //end class Overload §The compiler would not know how to distinguish between the two square methods.

Overloading §Overloading methods are distinguished by their signature -- a combination of the method’s name and its parameter types §Methods can not be distinguished by return type §Creating overloaded methods with identical parameters lists and different return types is a syntax error

Overloading and overriding §A redefinition of a superclass method in a subclass need not have the same signature as the superclass method. Such a redefinition is not method overriding; rather it is an example of overloading. §It is syntax error if a method in a superclass and a method in a subclass have the same signature but a different return type.

Shape Classes §We have a class called Shape l assume all shapes have x and y coordinates override Object's version of toString §Two subclasses of Shape l Rectangle add a new method changeWidth l Circle

A Shape class public class Shape { private double dMyX, dMyY; public Shape() { this(0,0);} public Shape (double x, double y) { dMyX = x; dMyY = y; } public String toString() { return "x: " + dMyX + " y: " + dMyY; } public double getArea() { return 0; }

A Rectangle Class public class Rect extends Shape { private double dMyWidth, dMyHeight; public Rect(double width, double height) { dMyWidth = width; dMyHeight = height; } public String toString() { return " width " + dMyWidth + " height " + dMyHeight; } public double getArea() { return dMyWidth * dMyHeight; } public void changeWidth(double width){ dMyWidth = width; }

class Circle extends Shape { private double radius; private static final double PI = ; public Circle(double rad){ radius = rad; } public double getArea() { return PI * radius * radius; } public String toString() { return " radius " + radius; } A Circle Class

Polymorphism §If class Rect is derived from class Shape, an operation that can be performed on an object of class Shape can also be performed on an object of class Rect §When a request is made through a superclass reference to use a method, Java choose the correct overridden method polymorphically in the appropriate subclass associated with the object §Polymorphism means “different forms”

Object Variables §Assume class Rect is a subclass of class Shape, and it overrides the method getArea(). §Does this work? Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea());

Object Variables §The above code works if Rect extends Shape §An object variable may point to an object of its base type or a descendant in the inheritance chain l The is-a relationship is met. A Rect is-a shape so s may point to it §This is a form of polymorphism and is used extensively in the Java Collection classes l Vector, ArrayList are lists of Objects Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea());

More Polymorphism §Assuming Circle and Rect are subclasses of Shape, and have both overridden toString(), which version gets called? Circle c = new Circle(5); Rect r = new Rect(5, 3); Shape s = null; if( Math.random(100) % 2 == 0 ) s = c; else s = r; System.out.println( "Shape is " + s.toString() );

More Polymorphism §Assuming Circle and Rect have both overridden toString which version gets called? l code works because s is polymorphic l method call determined at run time by dynamic binding Circle c = new Circle(5); Rect r = new Rect(5, 3); Shape s = null; if( Math.random(100) % 2 == 0 ) s = c; else s = r; System.out.println( "Shape is " + s.toString() );

§Assume class Rect is a subclass of class Shape, and it has a new method changeWidth(double width), which its super class does not have. §Does this work? Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20);

§polymorphism allows s to point at a Rect object but there are limitations §The above code does not work §How can you modify it a little to make it work without changing the classes definitions? Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20); // syntax error

§polymorphism allows s to point at a Rect object but there are limitations §The above code does not work §Statically s is declared to be a shape l no changeWidth method in Shape class l must cast s to a rectangle; Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20); // syntax error Rect r = new Rect(5, 10); Shape s = r; ((Rect)s).changeWidth(20); //Okay

Problems with Casting §Does this work? Rect r = new Rect(5, 10); Circle c = new Circle(5); Shape s = c; ((Rect)s).changeWidth(4);

Problems with Casting §The following code compiles but an exception is thrown at runtime §Casting must be done carefully and correctly  If unsure of what type object will be then use the instanceof operator Rect r = new Rect(5, 10); Circle c = new Circle(5); Shape s = c; ((Rect)s).changeWidth(4);

instanceof §syntax: expression instanceof ClassName Rect r = new Rect(5, 10); Circle c = new Circle(5); Shape s = c; if(s instanceof Rect) ((Rect)s).changeWidth(4);

Assume Manual is a Book, and Book is a Publication. Output? public class InstanceofDemo { public static void main(String args[]) { Publication pub1 = new Publication(); Book book1 = new Book(); Manual manual1 = new Manual(); if (pub1 instanceof Book) System.out.println(“pub1 is a Book”); if (book1 instanceof Book) System.out.println(“book1 is a Book”); if (manual1 instanceof Book) System.out.println(“manual1 is a Book”); } instanceof example (syntax: expression instanceof ClassName)

Casting §It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be omitted. For example, Circle c1 = new Circle(5); l Shape s = c1; is equivalent to l Shape s = (Shape)c1; §Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. l Circle c2 = (Circle) s;

Implicit Subclass-Object-to-Superclass- Object Conversion §Four possible ways to mix and match superclass references and subclass references with superclass objects and subclass objects l refer to a superclass object with a superclass reference l refer to a subclass object with a subclass reference l referring to a subclass object with a superclass reference is safe, but such code can only refer to superclass members l referring to a superclass object with a subclass reference is a syntax error

The role of final in Inheritance  A class may be declared as final l that class may not be extended  A method in a class may be declared as final l that method may not be overridden l guarantees behavior in all descendants can speed up a program by allowing static binding (binding or determination at compile time what code will actually be executed) §All static methods and private methods are implicitly final, as are all methods of a final class.

Abstract Classes and Methods §An abstract class defines a common interface for the various members of a class hierarchy. l an object of that type never exists and can never be instantiated. l a Shape or a Mammal §a method may be declared abstract in its header, after visibility modifier l no body to the method l all derived classes must eventually implement this method (or they must be abstract as well) l any class with 1 or more abstract methods must be an abstract class

abstract class Shape { public Shape() { id = ++count; } public int getId() { return id; } public abstract double getArea(); private static int count = 0; private int id; }

class Rectangle extends Shape { public Rectangle(int ul_x, int ul_y, int lr_x, int lr_y) { upperLeft = new Point(ul_x, ul_y); lowerRight = new Point(lr_x, lr_y); } public double getArea() { double result = Math.abs(upperLeft.x - lowerRight.x) * Math.abs(upperLeft.y - lowerRight.y); return result; } private Point upperLeft; private Point lowerRight; }

import java.awt.Point; class Circle extends Shape { public Circle(int x, int y, int rad) { center = new Point(x, y); radius = rad; } public double getArea() { return 4 * Math.atan(1.0) * radius * radius; // pi == 4 * atan(1.0) } private int radius; private Point center; }

Genericity §One of the goals of OOP is the support of code reuse to allow more efficient program development §If an algorithm is essentially the same, but the code would vary based on the data type genericity allows only a single version of that code to exist l some languages support genericity via templates l in Java, polymorphism and the inheritance requirement along with interfaces are used

Multiple Inheritance §Inheritance models the "is-a" relationship between real world things §one of the benefits is code reuse, completing programs faster, with less effort §in the real world a thing can have "is-a" relationships with several other things l a Graduate Teaching Assistant is-a Graduate Student. Graduate Teaching Assistant is-a Employee l a Student is-a Person. a Student is a SortableObject

Interfaces  A Java interface is a "pure abstract class". l Design only, no implementation. §Interfaces are declared in a way similar to classes but l consist only of public abstract methods l public final fields §A Java class extends exactly one other class, but can implement as many interfaces as desired

Common Interfaces in Java  One of the most interesting interfaces is: Comparable §compareTo should return an int 0 if the calling object is greater than the parameter package java.lang public interface Comparable { public int compareTo( Object other ); }

§If a class declares that it will implement an interface, but does not provide an implementation of all the methods in that interface, that class must be abstract Implementing an Interface public class Card implements Comparable{ public int compareTo(Object otherObject){ Card other = (Card)otherObject; int result = mySuit - other.mySuit; if(result == 0) result = myValue - other.myValue; return result; } // other methods not shown }

Polymorphism Again public static sort(Comparable[] list) { Comparable temp; int smallest; for(int i = 0; i < list.length - 1; i++) { small = i; for(int j = i + 1; j < list.length; j++) { if( list[j].compareTo(list[small]) < 0) small = j; } // end of j loop temp = list[i]; list[i] = list[small]; list[small] = temp; } // end of i loop }