C h 04 oop_inheritance

22
Chapter 04: Object Oriented Programming - Inheritance - - Inheritance -

description

 

Transcript of C h 04 oop_inheritance

Page 1: C h 04 oop_inheritance

Chapter 04:Object Oriented Programming

- Inheritance -

Chapter 04:Object Oriented Programming

- Inheritance -

Page 2: C h 04 oop_inheritance

public class Employee {private String name;

public Employee(Stringname){this.name=name;}public Employee(){name="No Name";}

public String toString(){return name;}}

public class Full extends Employee {private float salary;

public Full(String name, float salary){super(name);this.salary=salary;}

public Full(float salary){this.salary=salary;}

public String toString(){returnsuper.toString()+"\t"+salary;}public void inrcSalary(float x){salary += x;}}

public class Part extends Employee {private float perHour;private float noOfHours;

public Part(String name, float perHour, floatnoOfHours){ super(name); this.perHour=perHour;this.noOfHours=noOfHours;}

public Part(float perHour){this.perHour=perHour;}public String toString(){returnsuper.toString()+"\t"+perHour+"\t"+noOfHours;}public void inrcnoOfHours(float x){noOfHours += x;}public float paid(){return perHour * noOfHours;}}

public class Full extends Employee {private float salary;

public Full(String name, float salary){super(name);this.salary=salary;}

public Full(float salary){this.salary=salary;}

public String toString(){returnsuper.toString()+"\t"+salary;}public void inrcSalary(float x){salary += x;}}

public class Part extends Employee {private float perHour;private float noOfHours;

public Part(String name, float perHour, floatnoOfHours){ super(name); this.perHour=perHour;this.noOfHours=noOfHours;}

public Part(float perHour){this.perHour=perHour;}public String toString(){returnsuper.toString()+"\t"+perHour+"\t"+noOfHours;}public void inrcnoOfHours(float x){noOfHours += x;}public float paid(){return perHour * noOfHours;}}

public class Test {public static void main(String[] args) {Full fe1= new Full("Ahmad", 1000f);Full fe2= new Full(2000f);System.out.println(fe1+"\n"+fe2);Part pe3=new Part("Rami",20f,50f);Part pe4=new Part(35f);pe3.inrcnoOfHours(50);System.out.println(pe3+"\n"+pe4);}}

Page 3: C h 04 oop_inheritance

public class Full extends Employee {private float salary;

public Full(String name, float salary){super(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;}

{

public class Employee{private String name;

public Employee(Stringname){this.name=name;}public Employee(){name="No Name";}

public void setName(Stringname){this.name=name;}

public String toString(){return name;}{

public class Full extends Employee {private float salary;

public Full(String name, float salary){super(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;}

{

public class Employee{private String name;

public Employee(Stringname){this.name=name;}public Employee(){name="No Name";}

public void setName(Stringname){this.name=name;}

public String toString(){return name;}{

Page 4: C h 04 oop_inheritance

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

• 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 calleda 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.

Page 5: C h 04 oop_inheritance

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

• 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

Page 6: C h 04 oop_inheritance

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

• “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

Page 7: C h 04 oop_inheritance

Superclasses and Subclasses

– Superclass typically represents larger set ofobjects than subclasses

• Example:– superclass: Vehicle

» Cars, trucks, boats, bicycles, …– subclass: Car

» Smaller, more-specific subset of vehicles

– Superclass typically represents larger set ofobjects than subclasses

• Example:– superclass: Vehicle

» Cars, trucks, boats, bicycles, …– subclass: Car

» Smaller, more-specific subset of vehicles

Page 8: C h 04 oop_inheritance

Inheritance Hierarchy

• Inheritance relationships: tree-like hierarchy structure

Inheritance hierarchy for university CommunityMembers

CommunityMemberCommunityMember

EmployeeEmployee StudentStudent AlumnusAlumnus

• Inheritance relationships: tree-like hierarchy structure

Inheritance hierarchy for university CommunityMembers

StaffStaffFacultyFaculty

AdministratorAdministrator TeacherTeacher

Page 9: C h 04 oop_inheritance

Inheritance Hierarchy

ShapeShape

TwoDimensionalShapeTwoDimensionalShape ThreeDimensionalShapeThreeDimensionalShape

Inheritance hierarchy for Shapes.

CircleCircle SquareSquare TriangleTriangle SphereSphere CubeCube TetrahedronTetrahedron

Page 10: C h 04 oop_inheritance

protected Members

• protected access– Intermediate level of protection betweenpublic 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 (.)

• protected access– Intermediate level of protection betweenpublic 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 (.)

Page 11: C h 04 oop_inheritance

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 superclassimplementation

– superclass implementation changes may result in subclassmodifications

• 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 superclassimplementation

– superclass implementation changes may result in subclassmodifications

Page 12: C h 04 oop_inheritance

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 inheritsthe package-accessmembers 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 theone in the superclass, thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in thesuperclass.

• A subclass inherits all of the public and protected members of itsparent, no matter what package the subclass is in.

• If the subclass is in the same package as its parent, it also inheritsthe package-accessmembers 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 theone in the superclass, thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in thesuperclass.

Page 13: C h 04 oop_inheritance

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 thesame signature as the one in the superclass, thus overriding it.

• You can write a new static method in the subclass that has thesame signature as the one in the superclass, thus hiding it.

• You can declare new methods in the subclass that are not in thesuperclass.

• You can write a subclass constructor that invokes the constructor ofthe superclass, either implicitly or by using the keyword super.

• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has thesame signature as the one in the superclass, thus overriding it.

• You can write a new static method in the subclass that has thesame signature as the one in the superclass, thus hiding it.

• You can declare new methods in the subclass that are not in thesuperclass.

• You can write a subclass constructor that invokes the constructor ofthe superclass, either implicitly or by using the keyword super.

Page 14: C h 04 oop_inheritance

Example

Point/circle inheritance hierarchy• Point

– x-y coordinate pair– Methods:

• Circle– x-y coordinate pair– Radius

Point/circle inheritance hierarchy• Point

– x-y coordinate pair– Methods:

• Circle– x-y coordinate pair– Radius

Page 15: C h 04 oop_inheritance

PointClass

public class Point extends Object {

protected int x, y; // coordinates of the Point

public Point() // no-argument constructor

{

x = 0;

y = 0;

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

public class Point extends Object {

protected int x, y; // coordinates of the Point

public Point() // no-argument constructor

{

x = 0;

y = 0;

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

Page 16: C h 04 oop_inheritance

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

}

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

}

Page 17: C h 04 oop_inheritance

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

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

Page 18: C h 04 oop_inheritance

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

}

} // end class Test

public 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

}

} // end class Test

Point constructor: [0, 0]Point constructor: Center = [72, 29]; Radius = 0.0Circle constructor: Center = [72, 29]; Radius = 4.5Point constructor: Center = [5, 5]; Radius = 0.0Circle constructor: Center = [5, 5]; Radius = 10.0Circle finalizer: Center = [5, 5]; Radius = 10.0Point finalizer: Center = [5, 5]; Radius = 10.0Circle finalizer: Center = [72, 29]; Radius = 4.5Point finalizer: Center = [72, 29]; Radius = 4.5Point finalizer: [0, 0]

Page 19: C h 04 oop_inheritance

Object Class

• All classes in Java inherit directly or indirectly from the Objectclass (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.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.

Page 20: C h 04 oop_inheritance

Object Class (cont.)notify()

Wakes up a single thread that is waiting on this object's monitor.notifyAll()

Wakes up all threads that are waiting on this object's monitor.

wait()Causes the current thread to wait until another thread invokes the notify() method

or 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)Causes the current thread to wait until either another thread invokes

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

Page 21: C h 04 oop_inheritance

public class Point implements Cloneable{----------------public Object clone() // raise visibility level to public{

try{ return super.clone();}catch (CloneNotSupportedException e) { return null; }

}}

---------------}

Object Cloning

public 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

Page 22: C h 04 oop_inheritance

public class Test {public static void main( String args[] )

{ Point p1=new Point(10,30);Point p2=new Point(10,30);

if(p1.equals(p2)){ System.out.println("they are equals");}

if(Point.equals(p1,p2)){ System.out.println("they are equals");}

} // end class Test

public class Point{protected int x, y;

public void setx(int x){this.x=x;}public void multiply(Point p){

this.x=p.x*p.x;this.y=p.y*p.y;}public static void multiply(Point p1, Point p2){p1.x= p2.x *p2.x;p1.y= p2.y *p2.y;}

public static boolean equals(Point p1, Point p2){if(p1.x==p2.x && p1.y==p2.y)return true;return false;}public boolean equals(Object y){

Point p=(Point)y;if(this.x==p.x && this.y==p.y)return true;return false;}

public String toString() {return "[" + x + ", " + y + "]"; }

} // end class Point

equals method

public class Test {public static void main( String args[] )

{ Point p1=new Point(10,30);Point p2=new Point(10,30);

if(p1.equals(p2)){ System.out.println("they are equals");}

if(Point.equals(p1,p2)){ System.out.println("they are equals");}

} // end class Test

public class Point{protected int x, y;

public void setx(int x){this.x=x;}public void multiply(Point p){

this.x=p.x*p.x;this.y=p.y*p.y;}public static void multiply(Point p1, Point p2){p1.x= p2.x *p2.x;p1.y= p2.y *p2.y;}

public static boolean equals(Point p1, Point p2){if(p1.x==p2.x && p1.y==p2.y)return true;return false;}public boolean equals(Object y){

Point p=(Point)y;if(this.x==p.x && this.y==p.y)return true;return false;}

public String toString() {return "[" + x + ", " + y + "]"; }

} // end class Point