Chapter 04 inheritance

2,926 views

Published on

not 100% wrote by the author.just to share.

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,926
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
87
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Chapter 04 inheritance

  1. 1. 1Chapter 04: Inheritance
  2. 2. 2Objectives• Learn about the concept of inheritance• Extend classes• Override superclass methods• Understand how constructors are called during inheritance• Use superclass constructors that require arguments• Access superclass methods• Learn which methods you cannot override
  3. 3. 3Learning About the Conceptof Inheritance• Inheritance ▫ Mechanism that enables one class to inherit behavior and attributes of another class ▫ Apply knowledge of general category to more specific objects
  4. 4. 4Concept of Inheritance
  5. 5. 5
  6. 6. 6• Use inheritance to create derived class ▫ Save time ▫ Reduce errors ▫ Reduce amount of new learning required to use new class
  7. 7. 7• Base class ▫ Used as a basis for inheritance ▫ Also called: Superclass Parent class
  8. 8. 8Learning About the Conceptof Inheritance (continued)• Derived class ▫ Inherits from a base class ▫ Always “is a” case or example of more general base class ▫ Also called: Subclass Child class
  9. 9. 9Extending Classes• Keyword extends ▫ Achieve inheritance in Java ▫ Example: public class EmployeeWithTerritory extends Employee• Inheritance one-way proposition ▫ Child inherits from parent, not other way around• Subclasses more specific• instanceof keyword
  10. 10. 10Extending Classes
  11. 11. 11Quick Quiz1. ____ is the principle that allows you to apply your knowledge of a general category to more specific objects.2. True or False: A class diagram consists of arectangle divided into five sections.3. You use the keyword ____ to achieve inheritancein Java.
  12. 12. 12Extra notes
  13. 13. Inheritance Relationship• The inheritance relationship can be viewed as a relationship between an object category and its subcategories. ▫ For example...
  14. 14. Inheritance Relationship Transport
  15. 15. Inheritance Relationship Transport Air Transport
  16. 16. Inheritance Relationship Transport Air Transport Sea Transport
  17. 17. Inheritance Relationship Transport Air Transport Sea Transport Land Transport
  18. 18. Inheritance Relationship• The inheritance relationship is sometimes called the “is-a” relationship. ▫ For example...
  19. 19. Inheritance Relationship Transport Inheritance Relationship Sea Transport Land Transport Air Transport Sea Transport Land Transport Air Transport object “is a” object “is a” object “is a” Transport object Transport object Transport object
  20. 20. Inheritance Relationship• Based on the meaning of the “is-a” relationship, each object will have attributes and behaviour as defined by its category and all its supercategories.• An inheritance hierarchy can be built through generalization or specialization.
  21. 21. Inheritance Relationship Transport Attributes speed speed getSpeed( ) altitude Air Transport Behaviour getSpeed() altitude fly( ) fly()
  22. 22. Subclassing• Java supports class inheritance through subclassing.• By declaring a class as a subclass of a base class, an inheritance relationship between those two classes is created.• The Java keyword for this is extends.
  23. 23. Subclassing class Rectangle { private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public int getArea() { return width * height; } } class Square extends Rectangle { Basesubclass } class
  24. 24. Subclassing• In the example, the Square class is declared as a subclass of the Rectangle class• Each subclass inherits the instance variables and instance methods of its base class.• Note that constructors and private methods ARE NOT INHERITED.• Besides attributes and methods inherited from its base class, a subclass can also define its own attributes and methods.
  25. 25. Subclassing class AudioPlayer { class AudioPlayer { private String audioFilename; private String audioFilename; public AudioPlayer() {…} public AudioPlayer() {…} public void play() {…} public void play() {…} private void convert() {…} private void convert() {…} } } class MP3Player extends AudioPlayer { { class MP3Player extends AudioPlayer private boolean encrypted; private boolean encrypted; public MP3Player() {…} public MP3Player() {…} }} Attributes: audioFilename encrypted : MP3Player Constructor: MP3Player() Instance method: play()
  26. 26. Constructors and super()• Although a subclass inherits private attributes from its base class, it has no direct access to them. How will the subclass be able to initialize those attributes in its constructors?• Every constructor defined in a subclass must “call” one of the constructors of its base class. The “call” is performed through the super() statement.• The super() statement must be the first statement in the constructor method.
  27. 27. Constructors and super() class Rectangle { private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public int getArea() { return width * height; } } class Square extends Rectangle { “Calls” the constructor of the public Square(int size) { Rectangle class super(size, size); } }
  28. 28. Constructors and super()• Note that if there is no super() statement in a constructor, the compiler will automatically insert a super() statement with no parameters.
  29. 29. Constructors and super()class Rectangle { class Square extends Rectangle { private int width, height; public Square(int size) { setWidth(size); public Rectangle(int w, int h) { setHeight(size); width = w; } height = h; } } Compiler secretly adds public void setWidth(int w) { a super()! width = w; } The compiler then displays this error public void setHeight(int h) { height = h; message. Why? } test.java: 16: cannot resolve symbol symbol : constructor Rectangle ()} location: class Rectangle public Square(int size) { ^
  30. 30. Benefits of Inheritance• Reduces redundant code and code modifications ▫ A base class defines attributes and methods which are inherited by all of its subclasses. This leads to a reduction of redundant code and code modifications.• Makes your program easier to extend ▫ When adding a new subclass, we only need to define attributes and methods which are specific to objects of that class.
  31. 31. Benefits of Inheritance • Increases code reuse ▫ Example: The Java library has a JButton class. We can create a subclass of the JButton class to define objects which are like JButton objects but with additional attributes and methods. ▫ This is possible even though we do not have access to the source code for the JButton class.
  32. 32. Method Overriding• A subclass sometimes inherits instance methods whose implementation is not suitable for its instances. For example …
  33. 33. class Circle { private int radius; public Circle(int r) { radius = r; } public double getArea( ) { System.out.print("(Area calculated in Circle::getArea()) "); return 22.0/7*radius*radius;} }class Point extends Circle { The Point class inherits private int x, y; the radius attribute and public Point(int px, int py) the getArea() method { from its base class. super(0); x = px; y = py; }}
  34. 34. class Application { public static void main(String[ ] args) { Circle circle = new Circle(7); Point pt = new Point(100, 50); System.out.println(“Area of circle: "+circle.getArea()); System.out.println("Area of point: "+pt.getArea()); } } Output: (Area calculated in Circle::getArea()) Area of circle: 154.0 (Area calculated in Circle::getArea()) Area of point: 0.0• The area for any Point object is zero. For efficiency, it is unnecessary to calculate the area; simply return the value 0.
  35. 35. Method Overriding• Java supports method overriding. Method overriding means replacing the implementation of an inherited method with another implementation.• To override a method, we simply redefine the method in the subclass.• For example …
  36. 36. class Circle { private int radius; public Circle(int r) { radius = r; } public double getArea( ) { System.out.print("(Area calculated in Circle::getArea()) "); return 22.0/7*radius*radius; }}class Point extends Circle { private int x, y; Method getArea() overriden public Point(int px, int py) { super(0); x = px; Returns 0 y = py; } public double getArea( ) { System.out.print("(Area calculated in Point::getArea()) "); return 0; }}
  37. 37. Method Overriding class Application { public static void main(String[ ] args) { Circle circle = new Circle(7); Point pt = new Point(100, 50); System.out.println(“Area of circle: "+circle.getArea()); System.out.println("Area of point: "+pt.getArea()); } } Output: (Area calculated in Circle::getArea()) Area of circle: 154.0 (Area calculated in Point::getArea()) Area of point: 0.0
  38. 38. Method Overriding hierarchy:• Consider the following inheritance A D objD = new D(); doThis() E objE = new E(); B objB = new B(); C D objE.doThis(); doThis() objD.doThis(); objB.doThis(); E F doThis() B
  39. 39. The super keyword again…• Consider the following class definitions: class Rectangle { … private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public void display( ) { for (int row=0; row < height; row++) { for (int col=0; col < width; col++) System.out.print(*); System.out.println(); } } … }
  40. 40. Rectangle class is the base class for this subclassclass LabelledRectangle extends Rectangle { private String label; public LabelledRectangle(int w, int h, String str) { super(w, h); label = str; Overrides display() } method inherited from the base class public void display( ) { System.out.println("================="); for (int row=0; row < height; row++) { for (int col=0; col < width; col++) System.out.print(*); System.out.println(); } System.out.println(label); System.out.println("================="); } …}
  41. 41. Method Overriding class Application { public static void main(String[ ] args) { Rectangle rect1 = new Rectangle(3, 3); LabelledRectangle rect2; rect2 = new LabelledRectangle(2, 3, "Block"); rect1.display(); System.out.println(); rect2.display(); } }*********=================******Block=================
  42. 42. • Observe the body of the display() method in the LabelledRectangle class… public void display( ) { System.out.println("================="); for (int row=0; row < getHeight(); row++) { for (int col=0; col < getWidth(); col++) System.out.print(*); System.out.println(); } System.out.println(label); System.out.println("================="); } Is it possible to “call” the Exactly the same as the code in the overridden display() method display() method in the Rectangle class? inherited from the base class
  43. 43. • We can “call” the overridden method by using the super keyword as follows:class LabelledRectangle extends Rectangle { Executes the private String label; overridden method public LabelledRectangle(int w, int h, String str) { super(w, h); label = str; } public void display( ) { System.out.println("================="); super.display(); System.out.println(label); System.out.println("================="); }…}

×