Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Similar presentations


Presentation on theme: "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"— Presentation transcript:

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

2 Chapter 10 Class Inheritance
(Chapter 10 of the Textbook)

3 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

4 What Inheritance is: The Basic Concept

5 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.

6 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

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

8 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

9 Chains of Inheritance

10 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%

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

12 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

13 Calling Superclass Constructor

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

15 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( ) { }

16 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…

17 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!

18 Inheritance, Fields, and Methods

19 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.

20 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

21 Overriding Superclass Methods

22 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

23 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

24

25 The Final Modifier

26 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.

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

28 The Protected Access Modifier

29 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

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

31 The Object Class

32 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.

33 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

34 Abstract Classes

35 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?

36 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

37 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?

38 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;

39 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()

40 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;

41 Abstract Classes and Methods

42 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

43 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

44 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);

45 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

46 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

47 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) tag

48 Polymorphism

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

50 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

51 Interfaces

52 Domestic Animal Control Program

53

54

55

56

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

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

59 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

60 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

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

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

63 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 }

64 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.

65 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

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

67 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

68 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.

69 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.


Download ppt "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"

Similar presentations


Ads by Google