Your SlideShare is downloading. ×
C h 04 oop_inheritance
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

C h 04 oop_inheritance

378
views

Published on

Published in: Technology, Business

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
378
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
21
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Chapter 04:Object Oriented Programming - Inheritance -
  • 2. public class Employee { public class Part extends Employee {private String name; private float perHour; private float noOfHours;public Employee(Stringname){this.name=name;} public Part(String name, float perHour, floatpublic Employee(){name="No Name";} noOfHours){ super(name); this.perHour=perHour; this.noOfHours=noOfHours;}public String toString(){return name;}} public Part(float perHour) {this.perHour=perHour;}public class Full extends Employee { public String toString(){returnprivate float salary; super.toString()+"t"+perHour+"t"+noOfHours;} public void inrcnoOfHours(float x)public Full(String name, float salary){ {noOfHours += x;}super(name); public float paid(){return perHour * noOfHours;}}this.salary=salary;} public class Test { public static void main(String[] args) {public Full(float salary){this.salary=salary;} Full fe1= new Full("Ahmad", 1000f); Full fe2= new Full(2000f);public String toString(){return System.out.println(fe1+"n"+fe2);super.toString()+"t"+salary;} Part pe3=new Part("Rami",20f,50f);public void inrcSalary(float x){salary += x;} Part pe4=new Part(35f);} pe3.inrcnoOfHours(50); System.out.println(pe3+"n"+pe4);}}
  • 3. public class Employee{ private String name; public Employee(String name){this.name=name;} public Employee(){name="No Name";}public class Full extends Employee {private float salary; public void setName(String name){this.name=name;}public Full(String name, float salary){ super(name); public String toString(){return name;}this.salary=salary;} {public Full(float salary){this.salary=salary;}public void setName(String name){super.setName("*"+name+"*");}public String toString(){returnsuper.toString()+ "t"+salary;}public void inrcSalary(float x){salary += x;}{
  • 4. Inheritance• Software reusability• Create new class from existing class – Absorb existing class’s data and behaviors – Enhance with new capabilities• A class that is derived from another class is called a subclass (also a derived, extended , or child class).• The class from which the subclass is derived is called a superclass (also a base class or a parent class).• Subclass extends superclass • Subclass – More specialized group of objects – Behaviors inherited from superclass » Can customize• Each subclass can become the superclass for future subclasses.
  • 5. Inheritance (cont.)• Class hierarchy – Direct superclass • Inherited explicitly (one level up hierarchy) – Indirect superclass • Inherited two or more levels up hierarchy – Single inheritance • Inherits from one superclass – Multiple inheritance • Inherits from multiple superclasses – Java does not support multiple inheritance
  • 6. Inheritance (cont.)• “is-a” vs. “has-a” – “is-a” • Inheritance • subclass object treated as superclass object • Example: Car is a vehicle – Vehicle properties/behaviors also car properties/behaviors – “has-a” • Composition • Object contains one or more objects of other classes as members • Example: Car has wheels
  • 7. Superclasses and Subclasses– Superclass typically represents larger set of objects than subclasses • Example: – superclass: Vehicle » Cars, trucks, boats, bicycles, … – subclass: Car » Smaller, more-specific subset of vehicles
  • 8. Inheritance Hierarchy• Inheritance relationships: tree-like hierarchy structure CommunityMember Employee Student Alumnus Faculty Staff Administrator Teacher Inheritance hierarchy for university CommunityMembers
  • 9. Inheritance Hierarchy Shape TwoDimensionalShape ThreeDimensionalShapeCircle Square Triangle Sphere Cube Tetrahedron Inheritance hierarchy for Shapes.
  • 10. protected Members• protected access – Intermediate level of protection between public and private – protected members accessible to • superclass members • subclass members • Class members in the same package – Subclass access superclass member • Keyword super and a dot (.)
  • 11. Relationship between Superclasses and Subclasses • Using protected instance variables – Advantages • subclasses can modify values directly • Slight increase in performance – Avoid set/get function call overhead – Disadvantages • No validity checking – subclass can assign illegal value • Implementation dependent – subclass methods more likely dependent on superclass implementation – superclass implementation changes may result in subclass modifications
  • 12. What You Can Do in a Subclass• A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in.• If the subclass is in the same package as its parent, it also inherits the package-access members of the parent.• You can use the inherited members as is, replace them, hide them, or supplement them with new members.• The inherited fields can be used directly, just like any other fields.• You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).• You can declare new fields in the subclass that are not in the superclass.
  • 13. What You Can Do in a Subclass (cont.)• The inherited methods can be used directly as they are.• You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.• You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.• You can declare new methods in the subclass that are not in the superclass.• You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
  • 14. ExamplePoint/circle inheritance hierarchy • Point – x-y coordinate pair – Methods: • Circle – x-y coordinate pair – Radius
  • 15. public class Point extends Object { protected int x, y; // coordinates of the Point public Point() // no-argument constructor {Point x = 0; y = 0;Class } System.out.println( "Point constructor: " + this ); public Point( int xCoordinate, int yCoordinate ) // constructor { x = xCoordinate; y = yCoordinate; System.out.println( "Point constructor: " + this ); } protected void finalize() // finalizer { System.out.println( "Point finalizer: " + this ); } // convert Point into a String representation public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point
  • 16. Circle Classpublic class Circle extends Point { // inherits from Point protected double radius; // no-argument constructor public Circle() { // implicit call to superclass constructor here radius = 0; System.out.println( "Circle constructor: " + this ); } // Constructor public Circle( double circleRadius, int xCoordinate, int yCoordinate ) { // call superclass constructor super( xCoordinate, yCoordinate ); radius = circleRadius; System.out.println( "Circle constructor: " + this); }
  • 17. Circle Class (cont.) protected void finalize() // finalizer { System.out.println( " Circle finalizer: " + this ); } // convert the circle into a String representation public String toString() { return "Center = " + super.toString() + "; Radius = " + radius; }} // end class Circle
  • 18. Point and Circle Testpublic class Test { // test when constructors and finalizers are called public static void main( String args[] ) { Point P = new Point(); Circle circle1, circle2; circle1 = new Circle( 4.5, 72, 29 ); circle2 = new Circle( 10, 5, 5 ); P = null; // mark for garbage collection circle1 = null; // mark for garbage collection circle2 = null; // mark for garbage collection System.gc(); // call the garbage collector } Point constructor: [0, 0] Point constructor: Center = [72, 29]; Radius = 0.0} // end class Test Circle constructor: Center = [72, 29]; Radius = 4.5 Point constructor: Center = [5, 5]; Radius = 0.0 Circle constructor: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [5, 5]; Radius = 10.0 Point finalizer: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: [0, 0]
  • 19. Object Class• All classes in Java inherit directly or indirectly from the Object class (package java.lang),• So, its 11 methods are inherited by all other classes.Method Summaryclone( ) Creates and returns a copy of this object.equals(Object obj) Indicates whether some other object is "equal to" this one.finalize() Called by the garbage collector on an object when garbage collection determinesthat there are no more references to the object.getClass() Returns the runtime class of this Object.hashCode() Returns a hash code value for the object.toString() Returns a string representation of the object.
  • 20. Object Class (cont.)notify() Wakes up a single thread that is waiting on this objects monitor.notifyAll() Wakes up all threads that are waiting on this objects monitor.wait() Causes the current thread to wait until another thread invokes the notify() methodor the notifyAll() method for this object.wait(long timeout) Causes the current thread to wait until either another thread invokesthe notify() method or the notifyAll() method for this object, or a specified amount oftime has elapsed.wait(long timeout, int nanos) Causes the current thread to wait until another thread invokes the notify() methodor the notifyAll() method for this object, or some other thread interrupts the currentthread, or a certain amount of real time has elapsed.
  • 21. Object Cloningpublic class Point implements Cloneable{----------------public Object clone() // raise visibility level to public{ try { return super.clone();} catch (CloneNotSupportedException e) { return null; } }} public class Test { public static void main( String args[] )-------- {------- Point p1=new Point(10,30);} Point p2= (Point) p1.clone(); p1.setx(500); System.out.println(p1+"n"+p2); }} // end class Test
  • 22. equals method public class Point{ protected int x, y; public void setx(int x){this.x=x;}public class Test { public void multiply(Point p){ public static void main( String args[] ) this.x=p.x*p.x; { Point p1=new Point(10,30); this.y=p.y*p.y;}Point p2=new Point(10,30); public static void multiply(Point p1, Point p2){ p1.x= p2.x *p2.x;if(p1.equals(p2)) p1.y= p2.y *p2.y;} { System.out.println("they are equals"); public static boolean equals(Point p1, Point p2){} if(p1.x==p2.x && p1.y==p2.y)return true; return false;}if(Point.equals(p1,p2)) public boolean equals(Object y){ { System.out.println("they are equals"); Point p=(Point)y;} if(this.x==p.x && this.y==p.y)return true; return false;}} // end class Test public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point