CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Inheritance Inheritance Reserved word protected Reserved word super
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,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance, Polymorphism, and Virtual Functions
Chapter 10: Inheritance and Polymorphism
Inheritance Chapter 11.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
What is inheritance? It is the ability to create a new class from an existing class.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
11-1 Chapter.9 Classes & Objects: Inheritance –What Is Inheritance? –Calling the Superclass Constructor –Overriding Superclass Methods –Protected Members.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second.
Chapter Topics Chapter 10 discusses the following main topics:
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Inheritance Starting Out with Java: From Control Structures.
Inheriatance. 9-2 What is Inheritance? Generalization vs. Specialization Real-life objects are typically specialized versions of other more general objects.
Programming in Java CSCI-2220 Object Oriented Programming.
More on Inheritance Chapter 11 Continued. Reminders Overloading – different signatures Overriding – same signatures Preventing overriding – use final.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
11-2  What Is Inheritance?  Calling the Superclass Constructor  Overriding Superclass Methods  Protected Members  Chains of Inheritance  The Object.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
© 2010 Pearson Addison-Wesley. All rights reserved. AN INTRODUCTION TO INHERITANCE.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse.
Chapter 11 Inheritance. Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Polymorphism Contents Forms of polymorphism
Polymorphism, Abstract Classes & Interfaces
Inheritance and Polymorphism
03/10/14 Inheritance-2.
Chapter 11: Inheritance and Polymorphism
by Tony Gaddis and Godfrey Muganda
Chapter 5 Hierarchies IS-A associations superclasses subclasses
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
An introduction to inheritance
Starting Out with Java: From Control Structures through Objects
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 9: Polymorphism and Inheritance
Inheritance, Polymorphism, and Virtual Functions
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism, Abstract Classes & Interfaces
Java Inheritance.
Fundaments of Game Design
Chapter 11 Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
Chapter 8 Inheritance Part 2.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2015

Chapter 10 Class Inheritance (Chapter 10 of the Textbook)

Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object class Polymorphism Abstract Classes and Abstract Methods Interfaces

What Inheritance is: The Basic Concept

Inheritance The Concept: Inheritance allows a new class to extend an existing one. The new class inherits the public methods and fields of the class that it extends.

An example of inheritance Human Class ----------------------------------- - double height - double weight - String name - int gender - Date dateOfBirth + computeAge(void) : int + set and get for all the Fields Woman extends Human ----------------------------------- boolean isPregnant boolean hasPlayedSoftBall boolean pageantBefore boolean cheerLeader + int set and get for all class fields + printInfo() : void Man extends Human ----------------------------------- boolean hasPlayedFootball boolean hasPlayedBaseball hasBeardAndOrMustache + set and get for all the Fields + printInfo(void) : void

Let’s create those three classes Human Class Woman Class Man Class See Inheritance Project

How do we know what can be inherited? Question of the Day How do we know what can be inherited? Inheritance: “is a” To know if you can use inheritance in your class, ask yourself if your class “is a” of the inherited class Examples: A poodle is a dog A flower is a plant A rectangle is a shape A motor is a car

Chains of Inheritance

Another Example of Inheritance Situation The final grade of students is based on a set of graded activities: All activities generate a score (0-100 points) Each activity has a different way of computing its score Each activity has its weight percentage into the final course grade Graded Activity How grade is applied Percentage of final grade Laboratory Number of correctly completed labs 25% Midterm Exam Number of corrected answers 35% Final exam Number of correct answers 40%

The inheritance tree Graded Activity Class Midterm Exam Class Final Exam Class Lab Activity Class

Grade Activity Class ----------------------------------- score : double percentage : double activityType : String ---------------------------------- + setScore(s : double) : void + getScore() : double + other setters and getters LaboratoryActivity ----------------------------------- completedLabs : int numberOfLabs : int + computeScore() Midterm Activity ----------------------------------- numberOfQuestions : int numberOfMisses : int + computeScore() + getActivityScore() : double + getPercentage Exams Activity ----------------------------------- numberOfQuestions : int numberOfMisses : int + computeScore() : void + setNumberOfQuestions() + getNumberOfQuestions() + other setters and getters FinalExame Activity ----------------------------------- numberOfQuestions : int numberOfMisses : int + computeScore() + getActivityScore() : double + getPercentage Midterm Activity -----------------------------------+ MidtermActivity( int numberOfMisses, int numberOfQuestions) sets the percentage sets the activityType FinalExam Activity ----------------------------------- + FinalExamActivity( int numberOfMisses, int numberOfQuestions) sets the percentage sets the activityType

Calling Superclass Constructor

Let’s refresh our memory about Constructors What does a constructor do? When is a constructor called?

Does every class have a constructor? Constructors are created when you use the “new” operation to create new objects from a class blue print ArrayList<String> listOfStudents = new ArrayList( ); You can use constructors to initialize class fields and automatically run methods to initialize whatever is necessary Example: see LaboratoryActivity class Does every class have a constructor? Yes. If you do not create one, Java will create a default constructor with no input arguments public DefaultConstructor( ) { }

Which constructor is called? When you create a new object from a sub-class, like Woman, which constructor is called? Is the constructor of the super class called when creating a sub-class object? Hint: Think about in the case that the super class initializes some fields Let’s do a test, let’s modify the HumanInheritanceTest project and see what happens…

As you know, a class can have multiple constructors Different signatures (input arguments) If your sub-class needs to execute a specific constructor of the super class then just call it from the sub-class constructor like this: Public SubClass2( ) { super(10); // do your stuff here } If a super class has not default constructor, the sub-class MUST call the super class constructor in its (sub-class) constructor!

Inheritance, Fields, and Methods

Inheritance, Fields and Methods Members of the superclass that are marked private: are not inherited by the subclass, exist in memory when the object of the subclass is created may only be accessed from the subclass by public methods of the superclass. Members of the superclass that are marked public: are inherited by the subclass, and may be directly accessed from the subclass.

Inheritance, Fields and Methods When an instance of the subclass is created, the non-private methods of the superclass are available through the subclass object. FinalExam exam = new FinalExam(); exam.setScore(85.0); System.out.println("Score = " + exam.getScore()); Non-private methods and fields of the superclass are available in the subclass. setScore(newScore); See Inheritance Project

Overriding Superclass Methods

Important Points to Remember A sub class can: Call methods from the super class. These methods are inherited by the sub class Can create new methods in its body that the super class does not have These new methods cannot be called by the super class Override existing methods from the super class When calling these methods, Java will use the sub class methods instead of the one from super class

Overriding Superclass Methods Both overloading and overriding can take place in an inheritance relationship. Overriding can only take place in an inheritance relationship. Example: See Example next slide SuperClass3.java, SubClass3.java, ShowValueDemo.java

The Final Modifier

Preventing a Method from Being Overridden The final modifier will prevent the overriding of a superclass method in a subclass. public final void message() If a subclass attempts to override a final method, the compiler generates an error. This ensures that a particular superclass method is used by subclasses rather than a modified version of it.

Example of Final Methods and Fields double i = Math.PI; public static final double PI = 3.14159265358979323846; You do not want anyone to override methods like SINE and COSINE public static final double sin(double a)

The Protected Access Modifier

Protected Members Protected members of class: Example: may be accessed by methods in a subclass, and by methods in the same package as the class. Example: GradedActivity2.java FinalExam2.java ProtectedDemo.java

Access Specifiers public ✔ protected ✘ no modifier private Modifier Class Package Subclass World public ✔ protected ✘ no modifier private

The Object Class

The Object Class All Java classes are directly or indirectly derived from a class named Object. Object is in the java.lang package. Any class that does not specify the extends keyword is automatically derived from the Object class. public class MyClass { // This class is derived from Object. } Ultimately, every class is derived from the Object class.

The Object Class Because every class is directly or indirectly derived from the Object class: every class inherits the Object class’s members. example: toString and equals. In the Object class, the toString method returns a string containing the object’s class name and a hash of its memory address. The equals method accepts the address of an object as its argument and returns true if it is the same as the calling object’s address. Example: ObjectMethods.java

Abstract Classes

Abstract Classes Shape Program Triangle Circle Square Pentagon Show the ShapesDemo program What would be needed to update this program to accept a new type of shape such as a Pentagon? How much of the original code needs to be changed when you implement this new shape?

There are lots of benefits by using inheritance this way!!! Abstract Classes There are lots of benefits by using inheritance this way!!! Basically no change in the existing code Just add new code into your project/package No need to test verified code Only the new code shall be tested Reduce costs and time to develop/release new version Avoid breaking the existing functionality

Abstract Classes The side effect of using inheritance this way!!! Discuss what happens if the new shape does not have a required method What happens with the output All methods expected from your application should be implemented How can you prevent someone to forget to implement all the necessary methods in the subclass?

The Concept of Abstract Classes public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName;

The Concept of Abstract Classes Shape Shape is an abstract class with no implementation of area() and perimeter() area() perimeter() Circle Rectangle area() perimeter() area() perimeter() Circle and Rectangle are concrete classes with their own separate implementations of the methods area() and Perimeter()

public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; public double perimeter() { return 2.0 * (length + width); public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area( ) { return Math.PI * radius * radius; public double perimeter( ) { return 2.0 * Math.PI * radius;

Abstract Classes and Methods

Abstract Class An abstract class cannot be instantiated, but other classes are derived from it. An Abstract class serves as a superclass for other classes. A class becomes abstract when you place the abstract key word in the class definition. public abstract class ClassName

Abstract Methods An abstract method has no body/code implementation and must be overridden in a subclass. An abstract method is a method that appears in a superclass, but expects to be overridden in a subclass. Example: See next page Student.java, CompSciStudent.java, CompSciStudentDemo.java

public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName; public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area() { return Math.PI * radius * radius; public double perimeter() { return 2.0 * Math.PI * radius; public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; public double perimeter() { return 2.0 * (length + width);

Abstract Methods Notice that the key word abstract appears in the header, and that the header ends with a semicolon. public abstract void setValue(int value); Any class that contains an abstract method is automatically abstract. If a subclass fails to override an abstract method, a compiler error will result. Abstract methods are used to ensure that a subclass implements the method. Note that methods that are implemented in the superclass do not have abstract keyword on them

Another Examples of the need for abstract classes You made a game that all the animals must jump and make noises However each animal has a different way of jumping and roar. So you abstract the jump and noise methods and whoever creates a new animal must implement those methods You create a pizza recipe program that tells you the steps for creating different types of pizza Since each pizza has different toppings, you abstract the listOfIngridients() method

Abstract Methods Converting the Shape superclass into an abstract class Placing the abstract in the class definition Placing the method signatures (method name, access, input arguments, and returning type) The @override tag

Polymorphism

The Concept of Polymorphism A Listof Shapes A container of Shape objects will execute their own area and perimeter methods

The Concept of Polymorphism public class ShapeShifter { public static void main (String [ ] args) { Shape [ ] shapeList = new Shape[5]; shapeList[0] = new Circle(3.0); shapeList[1] = new Rectangle(3.0, 4.0); shapeList[2] = new Rectangle(2.5, 7.5); shapeList[3] = new Circle(2.5); shapeList[4] = new Square(5.0); for (int i = 0; i < shapeList.length; i++) { System.out.print (shapeList[i].toString( ) + “ ” ); System.out.print (shapeList[i].area( ) + “ ”); System.out.println (shapeList[i].perimeter( )); } Create an array to hold objects of (derived from) class Shape Create objects of the derived classes and put them in shapeList Iterate through the list and show area and perimeter of shapes Each derived class object executes its own area and perimeter methods

Interfaces

Domestic Animal Control Program

Interface An Interface is a java file containing only method definitions, but no implementation: Example:

Interfaces Interface just define the methods signature: Public type Returning type Method name Input arguments Interface does not implement the method

A specific method in your program Interfaces Interfaces are like contracts! Both parties must agree and obey the rules defined in the contract I’ll call a method of your program I’ll handle that! A specific method in your program Java Virtual Machine I have been pressed Button Pressed

Java Development Team at Sun Systems But What Method? Java Development Team at Sun Systems Is it the same as Jared’s? What is Mara’s method name? It would be nice it they all use the same method name

Action Listener Interface public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Action Listener Interface You: “I promise to have such a method in my code Java Team: “We will call your actionPerformed”

Action Listener Interface private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) // your code here to handle the action // like converting kilometers to miles }

Fields in Interfaces An interface can contain field declarations: all fields in an interface are treated as final and static. Because they automatically become final, you must provide an initialization value. public interface Doable { int FIELD1 = 1, FIELD2 = 2; (Method headers...) } Any class that implements this interface has access to these variables.

Implementing Multiple Interfaces A class can be derived (extended ) from only one superclass. Java allows a class to implement multiple interfaces. When a class implements multiple interfaces, it must provide the methods specified by all of them. To specify multiple interfaces in a class definition, simply list the names of the interfaces, separated by commas, after the implements key word. public class MyClass implements Interface1, Interface2, Interface3

Interfaces in UML GradedActivity A dashed line with an arrow indicates implementation of an interface. FinalExam3 Relatable

Polymorphism with Interfaces Java allows you to create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its class type. This is another example of polymorphism. Example: RetailItem.java CompactDisc.java DvdMovie.java PolymorphicInterfaceDemo.java

Polymorphism with Interfaces In the example code, two RetailItem reference variables, item1 and item2, are declared. The item1 variable references a CompactDisc object and the item2 variable references a DvdMovie object. When a class implements an interface, an inheritance relationship known as interface inheritance is established. a CompactDisc object is a RetailItem, and a DvdMovie object is a RetailItem.

Polymorphism with Interfaces A reference to an interface can point to any class that implements that interface. You cannot create an instance of an interface. RetailItem item = new RetailItem(); // ERROR! When an interface variable references an object: only the methods declared in the interface are available, explicit type casting is required to access the other methods of an object referenced by an interface reference.