{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Prinlnim a d c c new d cprintname what

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: methods may only directly call other staAc methods. Similarly, staAc methods can only directly read/write staAc fields. Of course a staAc method can create instance of objects (via new) and then invoke methods on those objects. •  Gotcha: It is possible (but confusing) to invoke a staAc method as though it belongs to an object instance. –  e.g. o.someMethod(17) where someMethod is staAc –  Eclipse will issue a warning if you try to do this. Overriding & ASM A Subclass can Override its Parent public class C {! public void printName() { System.out.println(“I’m a C”); }! }! public class D extends C {! public void printName() { System.out.prinln(“I’m a D”); }! }! C c = new D();! c.printName(); // what gets printed?! •  Our model for dynamic dispatch already explains what will happen when we run this code. •  Useful for changing the default behavior of classes. •  But… can be confusing and difficult to reason about if not used carefully. Dangers of Overriding public class C {! Exam exam2 = …! public void printTest() {! if (onDate(”December 17")) {! System.out.println(“as scheduled”); ! } else { System.out.prinln(“postponed”); }! }! public boolean onDate(String s) { ! !return exam2.date().equals(s); ! }! }! public class D extends C {! Exam final = …! public boolean onDate(String s) { ! return final.date().equals(s); ! }! }! C c = new D();! c.printTest(); // what gets printed?! The C class might be in another package, or a library... Whoever wrote D might not be aware of the implicaAons of changing onDate. Overriding the method can cause the behavior of printTest to change! –  Overriding can break invariants/abstracAons relied upon by the superclass. When To Override? •  Only override methods when the parent class is designed specifically to support such modificaAons: –  If you’re wriAng the code for both the parent and child class (and will maintain control of both parts as the sojware evolves) it might be OK to overrride. –  If the library designer specifically describes the b...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online