1 / 20

159.234 LECTURE

159.234 LECTURE. 25. JAVA-3. Inheritance, Polymorphism, and Interfaces. Polymorphism. subclass1. subclass2. subclass3. Polymorphism + Interfaces = reduce duplication in programming effort. Immediate superclass. Parent class. subclass1. subclass2. subclass. subclass3.

Download Presentation

159.234 LECTURE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 159.234LECTURE 25 JAVA-3 Inheritance, Polymorphism, and Interfaces

  2. Polymorphism subclass1 subclass2 subclass3 Polymorphism + Interfaces = reduce duplication in programming effort Immediate superclass Parent class subclass1 subclass2 subclass subclass3 Object of different subclasses subclass = derived class Treat them as a single unit by referring to them as objects of their common superclass. Java is able to automatically apply the proper methods to each object, regardless of the subclass the object came from.

  3. Polymorphism Polymorphism + Interfaces = reduce duplication in programming effort • Subclass • inherits instance variables & methods (behaviours) • can add additional instance variables & methods • can override the behaviour of methods inherited from its parent class. Immediate superclass ParentClass p SubClass s * A subclass needs only to provide methods to implement the differences between itself and its parent. p must actually refer to a SubClass object when the program executes; otherwise, Java will throw a ClassCastException. p = s; //s is upcast to its ParentClass s = p; //illegal! Compile-time error! s = (SubClass) p ; //legal - downcast p into its subclass type

  4. Java Classes and Objects • Java Object Fundamentals • Method Overloading • Constructor Methods • Inheritance • Polymorphism • Abstract Classes • Interfaces • Inner Classes & Anonymous Classes • Overriding Methods • Final Modifier • Java Modifiers Summary

  5. Fundamental Ideas • data fields & methods • Functions (methods) arguments pass-by-value • this, super - references to current object & parent • data hiding and encapsulation • overloading method names • construction and initialisation and default constructor • sub-classing, instanceof and polymorphism • single inheritance and non inheritance of constructors • casts up and down class hierarchies See Examples

  6. overriding methods and accessing overridden methods using super • overloaded constructors • parent class constructors • class variables and methods - static • final - class (non extensible) final methods (not • override-able), final variables (constants) • abstract classes & interfaces • access modifiers • inner classes & anonymous classes • package grouping mechanism and import

  7. public class Overload{ public static void main( String args[] ) { inti[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; long l[] = { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; float f[] = { 0.0F, 2.0F, 4.0F, 6.0F, 8.0F, 10.0F }; double d[] = { 1.0, 3.0, 5.0, 7.0, 9.0 }; System.out.println("Sum i = " + sum( i ) ); System.out.println("Sum l = " + sum( l ) ); System.out.println("Sum f = " + sum( f ) ); System.out.println("Sum d = " + sum( d ) ); } public static long sum( int[] a ){ long summed = 0L; for(inti=0;i<a.length;i++){ summed += a[i]; } return summed; } public static long sum( long[] a ){ long summed = 0L; for(inti=0;i<a.length;i++){ summed += a[i]; } return summed; } public static double sum( float[] a ){ double summed = 0.0; for(inti=0;i<a.length;i++){ summed += a[i]; } return summed; } public static double sum( double[] a ){ double summed = 0.0; for(inti=0;i < a.length; i++){ summed += a[i]; } return summed; } } Method Overloading overload methods with different args and return types return type must not be the only distinction There is no operator overloading in Java Example Output: > java Overload Sum i = 55 Sum l = 88 Sum f = 30.0 Sum d = 25.0 Java allows several methods to be defined with the same name, as long as the methods have different sets of parameters (based on the number, types, and order of the parameters). See Overload.java

  8. public class ConstructorsextendsWorker{ public static void main( String args[] ) { Constructors a = new Constructors(); Constructors b = new Constructors("Label"); Constructors c = new Constructors(42); Constructors d = new Constructors(36,"Full"); System.out.println(a.amount + " " + a.label); System.out.println(b.amount + " " + b.label); System.out.println(c.amount + " " + c.label); System.out.println(d.amount + " " + d.label); } private int amount; Constructors(){ // constructor with no args this(0, "empty"); } Constructors(String s){ // four overloaded constructor methods this(0, s ); } Constructors(int i){ this(i, "empty"); } Constructors( int i, String s ){ super( s ); amount = i; } } class Worker{ String label; // default protection, so that // theConstructors class inherits it Worker( String str ){ // a single constructor method with an arg label = str; } } Constructor Methods do not inherit constructor system supplied constructor takes no arguments once overridden lose the use of the system supplied constructor can overload constructor can access other constructors using this() access parent's constructor using super() only one level of indirection allowed (no super.super() allowed ) Destruction is automatically done using garbage collection by the system. Example Output: > java Constructors 0 empty 0 Label 42 empty 36 Full > Calls on another Constructor of the same class Calls on Constructor of parent class

  9. public class Inheritanceextends Legacy{ public static void main(String args[]){ Inheritance i = new Inheritance(); System.out.println("i.toString() gives: " + i.toString() ); // toString() inherited from java.lang.Object i.setLegacy("money"); // set/getLegacy inherited from Legacy System.out.println("i.getLegacy() gives: " + i.getLegacy() ); } } class Legacyextends Object{ private String legacy; public void setLegacy( String something ){ legacy = something; } public String getLegacy(){ return legacy; } } Java Inheritance single inheritance (unlike C++) subclass inherits variables and methods from parent superclass Example results: > java Inheritance i.toString() gives:Inheritance@18c4387 i.getlegacy() gives: money > This is redundant as all java objects extend Object by default, unless they explicitly extend some other class. Accessible only to the subclass through the methods setlegacy() and getlegacy(). This is giving us some numeric value because the class Inheritance did not implement the method toString()

  10. public class Polymorph{ public static void main( String args[] ) { Mammal m; Human h = new Human(); Wolf w = new Wolf(); m = h; Mammal.describe(m); m = w; Mammal.describe(m); } } class Mammal{ public static void describe(Mammal x){ int legcount; if( x instanceof Human ){ legcount = ((Human)x).legs(); System.out.println("has higherBrain " + ((Human)x).higherBrain ); }else if ( x instanceof Wolf ){ legcount = ((Wolf)x).legs(); System.out.println("has tail " + ((Wolf)x).tail ); }else{ legcount = 0; } System.out.println(legcount + " legs" ); System.out.println("Temperature " + x.temperature ); } double temperature = 0.0; //defaults to package access, therefore visible in it’s sublclasses } class Humanextends Mammal{ public int higherBrain = 3; //data member Human(){ temperature = 37.5; } //constructor public int legs(){ return 2; } //method } class Wolfextends Mammal{ public int tail = 4; //data member Wolf(){ temperature = 29.0; } //constructor public int legs(){ return 4; } //method } Java Polymorphism superclass reference can contain subclass references casts possible Example results: > java Polymorph has higherBrain 3 2 legs Temperature 37.5 has tail 4 4 legs Temperature 29.0 > Downcasts Mammal x to Human

  11. public class AbstractionextendsDesign{ public static void main(String args[] ){ // Design d = new Design(); // not allowed to instantiate an // abstract class Abstraction a = new Abstraction(); a.start(1); a.stop(2); System.out.println(a.description()); } public void start(int x){ // must provide start and stop state = x; // or Abstraction will also be abstract } public void stop(int z){ state += z; } } abstract class Design{ public abstract void start( int x ); public abstract void stop( int y ); protected int state = 0; public String description(){ return "This conforms to the Design designation: " + state; } } Java Abstract Classes No method body cannot be instantiated used to embody a design and partial code Example Output: > java Abstraction This conforms to the Design designation: 3 > *Any class containing an abstract method, or failing to override an abstract method inherited from its superclass is an abstract class. This is required!

  12. Interfaces Interface Abstract class Class 3 Class 4 subclass2 subclass1 may contain method signatures and constants • has no direct inherited relationship with any particular class; they are defined independently • any class may choose to implement an interface by adding an implements clause to its class definition. If so, it should provide an implementation for every abstract method in the interface. The method should have exactly the same argument definition.

  13. Interfaces may contain method signatures and constants • use interfaces to create the same standard method definitions in many different classes. This will enable you to write a single method (e.g. sort, search, etc.) to manipulate all of the classes that implement the interface.

  14. public class Interfacial implements Template, Template2{ private int state = 0; public static void main(String args[] ){ Interfacial i = new Interfacial(); Template t = i; t.start(1); t.stop(2); Template2 t2 = i; System.out.println( t2.description() ); } public void start(int x){ // must provide start, stop & description state = x; // or compiler will flag non compliance } // to interface spec public void stop(int z){ state += z; } public String description(){ return "I conform"; } } // the interfaces would normally be in some other file and probably // have been written by someone else at some other time interface Template{ public void start( int x );// these abstract methods must have no body public void stop( int y ); // no member variables allowed in interface } interface Template2{ public String description(); } Java Interfaces like abstract classes but no bodies or variables, except constants used for interface specification -- equivalent to a C header file classes can implement as many interfaces as desired compiler will flag any non-compliance with interface specification implements interface is a bit like of a “promise” to provide the implied methods Example output: > java Interfacial I conform >

  15. Interfaces Class that implements two interfaces public class Robot{ protected void initialize(){ //Codes for initialize } protected void switchRole(){ //Codes for switchRole } protected void retreat(){ //Codes for retreat } } public class Attacker extends Robot implements TargetPursuit, ObstacleAvoidance{ // Code here does something } interface TargetPursuit{ public booleantargetDestroyed(int x, int y); public int distance(int x, int y); } interface ObstacleAvoidance{ public booleansafeDistance(); public void findObstacles(); }

  16. public class Inner{ private static int state = 79; public static void main(String args[]){ Inner i = new Inner(); i.doit(); } public void doit(){ Local l = new Local(); l.code = 45; // can access because Local is a member System.out.println( l.hero() ); } public class LocalextendsOuter{ private int code = 33; public String hero(){ state = 78; return "Local hero " + code + " " + state + " " + space; } } } //end of class Inner class Outer{ protected int space = 16; // accessible to subclasses } Inner Classes convenient to keep all relevant code local to the file also handy for 'hiding' code from use by other classes Example Output: > java Inner Local hero 45 78 16 > This is not allowed in C++! You cannot initialise a data member not unless it is constant See Inner.java

  17. public class Anonymous{ public static void main(String args[]){ Anonymous a = new Anonymous(); a.doit(); } public void doit(){ extract(new Dummy(){ // invokes extract() with an object of no name public String message( int z ){ return "This is a message made from the int " + z; } } ); // parenthesis matches that next to extract above } public void extract(Dummy d ){ System.out.println( d.message(42) ); } } interfaceDummy{ public String message(int x); } Anonymous Classes instantiated without a name useful for one-off interface compliance Example Output: > java Anonymous This is a message made from the int 42 >

  18. public class Override extends Parent{ public static void main(String args[]){ Override o = new Override(); System.out.println(o.message() ); System.out.println(o.text() ); } public String message(){// overrides the superclass's method return "to be or not to be"; } public String text(){ // must be at least as accessible as the // overridden method in the superclass return super.text() + " though thou be thrice times a fool"; } // can still invoke overridden method } //end of class Override class Parent{ public String message(){ return "I am thy father's spirit"; } protected String text(){// accesible from same package or any subclass return "Verily, verily I say unto thee"; } } Overriding Methods You can customise methods otherwise inherited from superclass overriding method must be at least as accessible as overridden method (unlike in C++) Example Output: > java Override to be or not to be Verily, verily I say unto thee though thou be thrice times a fool >

  19. public final class Final extends Note{ public static void main(String args[]){ Final o = new Final(); // PI = 4.2; // this line would cause compiler error System.out.println( PI + " " + o.name() ); } // a constant public static final double PI = 3.141592654; // String name() { return "Corruption"; } //this line would cause a compiler error } class Note{ final String name(){ // cannot be overridden return "Ultimatum note"; } } Final Modifier means class may not be extended means method cannot be overridden in a subclass means variable is a constant Example Output: > java Final 3.141592654 Ultimatum note > Static or private methods are automatically final. Final class cannot be a superclass. All methods in a final class are automatically final. Optimized by compiler You may declare commonly used methods that do not need to be inherited to be final.

  20. Java has only singleinheritance but has abstract classes and interfaces to support design ideas Polymorphism works with object references Java has modifiers to support access restrictions (encapsulation) and other common ideas in OO programming Summary

More Related