80 likes | 304 Views
Slide 1 / 8. Inheritance and Method Overriding. CS 100M AEW - Section 2 Jason Shapiro & Dave Golland. Basics of Inheritance. Inheritance & Method Overriding. Slide 2 / 8. subclass protected extends super( parameters ) method overriding. Rectangle Class.
E N D
Slide 1 / 8 Inheritance and Method Overriding CS 100M AEW - Section 2 Jason Shapiro & Dave Golland
Basics of Inheritance Inheritance & Method Overriding Slide 2 / 8 • subclass • protected • extends • super(parameters) • method overriding
Rectangle Class Inheritance & Method Overriding Slide 3 / 8 public class Rectangle{ protected int length, width; public Rectangle(int l, int w){ length= l; width= w; } publicdouble area(){ return length*width; } publicint perimeter(){ return 2*(length+width); } }
Square Class Inheritance & Method Overriding Slide 4 / 8 public class Square extendsRectangle{ public Square(int s){ super(s,s); } publicint sqArea(){ return Math.pow(length,2); } publicint perimeter(){ return 4*length; } publicdouble area(){ return Math.PI*Math.pow(length/2.0,2); } }
Client Code Inheritance & Method Overriding Slide 5 / 8 public class AEW { public static void main(String[] args){ Rectangle[] rect= new Rectangle[4]; rect[0]= new Rectangle(3,5); rect[1]= new Square(4); rect[2]= rect[0]; } }
What is the output? Inheritance & Method Overriding Slide 6 / 8 public class AEW { public static void main(String[] args){ Rectangle[] rect= new Rectangle[4]; rect[0]= new Rectangle(3,5); rect[1]= new Square(4); rect[2]= rect[0]; for(int i=0; i<rect.length; i++){ System.out.println(rect[i].area()); } } }
What is the output? Inheritance & Method Overriding Slide 7 / 8 public class AEW { public static void main(String[] args){ Rectangle[] rect= new Rectangle[4]; rect[0]= new Rectangle(3,5); rect[1]= new Square(4); rect[2]= rect[0]; System.out.println(rect[1].sqArea()); } }
Conclusion Inheritance & Method Overriding Slide 8 / 8 Object Type – follows newkeyword, the object’s type Reference Type – the declared type of the variable storing a reference to the object Method Overriding To see whether a method can be called, or which method will be called, remember the following information: 1) First, check reference type. If the method exists in this class, then it can be called. 2) Next, check object type. If the method exists in this class, then this, overriden, method is called.