Inheritance modifiers class Class Name extends Existing Class

  • Slides: 26
Download presentation
Inheritance ﺍﻟﻮﺭﺍﺛﺔ

Inheritance ﺍﻟﻮﺭﺍﺛﺔ

modifier(s) class Class. Name extends Existing. Class. Name modifier(s) { member. List }

modifier(s) class Class. Name extends Existing. Class. Name modifier(s) { member. List }

Inheritance: class Circle Derived from class Shape public class Circle extends Shape {. .

Inheritance: class Circle Derived from class Shape public class Circle extends Shape {. . . } Java Programming: From Problem Analysis to Program Design, Second Edition 5

public class Saving. Account extends Bank. Account // The Saving. Account constructor { public

public class Saving. Account extends Bank. Account // The Saving. Account constructor { public Saving. Account(double rate) { interest. Rate = rate; } // add. Interest method public void add. Interest() { double interest = get. Balance()*interest. Rate/100; deposit(interest); } // The Saving. Account instance variable private double interest. Rate; }

UML Class Diagram: class Rectangle Java Programming: From Problem Analysis to Program Design, Second

UML Class Diagram: class Rectangle Java Programming: From Problem Analysis to Program Design, Second Edition 20

UML Class Diagram: class Box Java Programming: From Problem Analysis to Program Design, Second

UML Class Diagram: class Box Java Programming: From Problem Analysis to Program Design, Second Edition 21

class Box public void print() { super. print(); System. out. print("; Height = "

class Box public void print() { super. print(); System. out. print("; Height = " + height); } public void set. Dimension(double l, double w, double h) { super. set. Dimension(l, w); if (h >= 0) height = h; else height = 0; } public double area() { return 2 * (get. Length() * get. Width() + get. Length() * height + get. Width() * height); Java Programming: From } Analysis to Program 23 Problem Design, Second Edition

Defining Constructors of the Subclass • Call to constructor of superclass: – Must be

Defining Constructors of the Subclass • Call to constructor of superclass: – Must be first statement. – Specified by super parameter list. public Box() { super(); height = 0; } public Box(double l, double w, double h) { super(l, w); height = h; } Java Programming: From Problem Analysis to Program Design, Second Edition 25

Objects my. Rectangle and my. Box Rectangle my. Rectangle = new Rectangle(5, 3); Box

Objects my. Rectangle and my. Box Rectangle my. Rectangle = new Rectangle(5, 3); Box my. Box = new Box(6, 5, 4); Java Programming: From Problem Analysis to Program Design, Second Edition 26