Lecture 7: Reusing Code & Interfaces CSE 116/504 – Intro. To Computer Science for Majors II Lecture 7: Reusing Code & Interfaces Lecture included 15 minute presentation by Bloomberg & three TopHat questions gauging student confidence in OO concepts
Announcements Score posted to UBLearns so you can track grades Calculated grades drop lowest 3 homeworks & 1 quiz Homework for week #3 due Monday at 12:45PM Tim Sweeney is the owner of Epic Games and was one of the major drivers of the Unreal Engine (among other things)
Inheritance Composition Sharing is Caring Often need to write classes sharing actions & data Could just cut-and-paste code between the classes If When bug found, must remember to fix both copies Cutting-and-pasting takes effort & have better things to OO languages (Java) offer two possible solutions: Inheritance & Composition
Composition Typically used for cases with a “has-a” relationship Student has a full name Full name has a first name Car has an engine Rectangle has an upper-right vertex
Use a field to compose classes Composition Data not really shared, but belong to specific class Odd to discuss the x-coordinate of a rectangle Discuss student's first name & despite FullName holding Use a field to compose classes So we would add name field to Student class firstName field in FullName class If must use data externally, add getters & setters
Composition Key Concept #1 When relationship between classes is Has A(n): Add fields
Composition Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student {
Composition Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public FullName getName() { return name; }
Composition Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public FullName getName() { return name; } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt");
Composition Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public FullName getName() { return name; } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt"); Copyrighted image of Mr. Yuk used under Educational & Fair Use exceptions. Original image was downloaded from: https://en.wikipedia.org/w/index.php?curid=25949108
Shouldn't Student control changing names? Composition Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public FullName getName() { return name; } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt"); Copyrighted image of Mr. Yuk used under Educational & Fair Use exceptions. Original image was downloaded from: https://en.wikipedia.org/w/index.php?curid=25949108 Composition + getters can make yucky code; Shouldn't Student control changing names?
Delegation Delegation improves composition of classes Goal creating classes & code easier to write, read, & use Not universal solution, but useful additional tool Important for larger projects & splitting work in groups Replace getters & add methods for needed actions Methods can act, but mostly delegate to field's methods Adds (slightly) to code size, but performance unchanged Trade-off worth it, since we write once but use frequently
Delegation Key Concept Image of Homer Simpson used under Parody & Fair Use exceptions. Original from: http://www.ebay.com/blogs/stories/cant-someone-else-just-do-it
Replace yuck-inducing getter method… Delegation Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public FullName getName() { return name; } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt"); Replace yuck-inducing getter method…
Delegation Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public void setFirstName(String newName) { name.setFirstName(newName); } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt"); Replace yuck-inducing getter method… … with method calling field's method
Reducing how much you must understand… Delegation Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public void setFirstName(String newName) { name.setFirstName(newName); } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ FullName fName = student.getName(); fName.setLastName("Jingleheimerschmidt"); Reducing how much you must understand…
Delegation Example public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public void setFirstName(String newName) { name.setFirstName(newName); } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ student.setLastName("Jingleheimerschmidt"); Reducing how much you must understand… …so writing & updating code becomes easier!
Composition + Delegation = public class FullName { private String firstName; private String lastName; // Constructor, getters & setters also here } public class Student { private FullName name; // Brevity is the soul of wit- Shakespeare public void setFirstName(String newName) { name.setFirstName(newName); } // In some other code that exists to demonstrate this point Student student = /* Code to create and initialize a Student instance*/ student.setLastName("Jingleheimerschmidt");
Composition Key Concept #1 When relationship between classes is Has a(n): Add fields & Delegate actions
Inheritance “Is-a” relationships implemented via inheritance Automobile is a Vehicle Car is a Vehicle Truck is an Automobile Car is an Automobile Subclass includes data and actions from superclass Adds more data or actions to extend definition further Some tasks in the superclass specialized in the subclass Classes related to each other as fundamental ideas
Inheritance “Is-a” relationships implemented via inheritance Automobile is a Vehicle Car is a Vehicle Truck is an Automobile Car is an Automobile Specify that subclass extends superclass Automobile extends Vehicle Truck extends Automobile Car extends Automobile (& Vehicle?)
Inheritance Key Concept #1 When relationship between classes is Is A(n): Use extends
extends Example Vehicle Automobile Car Truck public class Vehicle {…} public class Automobile extends Vehicle {…} public class Car extends Automobile {…} public class Truck extends Automobile {…} Vehicle Automobile Car Truck
Inheritance Key Concept #2 Every Java class extends exactly 1 class
extends Example extends explicitly specifies superclass for class Can skip & class automatically extends Object Object Vehicle Automobile Car Truck
extends Example public class Vehicle {…} public class Automobile extends Vehicle {…} public class Car extends Automobile {…} public class Truck extends Automobile {…} Object Vehicle Automobile Car Truck
extends Example No limit on subclasses which extend a specific class Automobile superclass of both Car & Truck Vehicle superclass of Automobile, Car, & Truck Object Vehicle Automobile Car Truck
Superclass (& Subclass) In Java, each and every class is subclass of: superclass
Superclass (& Subclass) In Java, each and every class is subclass of: superclass superclass’s superclass
Superclass (& Subclass) In Java, each and every class is subclass of: superclass superclass’s superclass superclass’s superclass’s superclass
Superclass (& Subclass) In Java, each and every class is subclass of: superclass superclass’s superclass superclass’s superclass’s superclass superclass’s superclass’s superclass’s superclass, … Object
Superclass (& Subclass) In Java, each and every class is subclass of: superclass superclass’s superclass superclass’s superclass’s superclass superclass’s superclass’s superclass’s superclass, … Object Automobile is-a Vehicle Since Truck is-an Automobile … …then Truck is-a Vehicle & … …also Truck is-an Object
Inheritance Key Concept #2 Every Java class extends 1 class directly and can inherit from many others via superclass
What Gets Inherited And How? Class inherits all fields & methods in superclass Does not matter if inherited from superclass's superclass Without extra typing use fields & call methods directly* Animal classification image used under a Creative Commons Attribution 2.0 Generic (CC BY 2.0) license. Original image by Siyavula Education and available at: https://www.flickr.com/photos/121935927@N06/13536384133
Inheritance Example public class Sailor { String str = "Aye, aye"; public String goal() { return "Capt."; } } public class Pirate extends Sailor { public String getRealGoal() { return "Dread Pirate " + goal(); } public Pirate() { str = "Yarr"; } public static void main(String[] args) { Pirate wesley = new Pirate(); Sailor popeye = new Sailor(); System.out.println(wesley.goal()); System.out.println(popeye.goal()); System.out.println(wesley.getRealGoal()); System.out.println(popeye.getRealGoal()); System.out.println(wesley.str); System.out.println(popeye.str);
Inheritance Example public class Sailor { String str = "Aye, aye"; public String goal() { return "Capt."; } } public class Pirate extends Sailor { public String getRealGoal() { return "Dread Pirate " + goal(); } public Pirate() { str = "Yarr"; } public static void main(String[] args) { Pirate wesley = new Pirate(); Sailor popeye = new Sailor(); System.out.println(wesley.goal()); System.out.println(popeye.goal()); System.out.println(wesley.getRealGoal()); System.out.println(popeye.getRealGoal()); System.out.println(wesley.str); System.out.println(popeye.str);
Inheritance Example Changes in subclass ONLY affect subclass; public class Sailor { String str = "Aye, aye"; public String goal() { return "Capt."; } } public class Pirate extends Sailor { public String getRealGoal() { return "Dread Pirate " + goal(); } public Pirate() { str = "Yarr"; } public static void main(String[] args) { Pirate wesley = new Pirate(); Sailor popeye = new Sailor(); System.out.println(wesley.goal()); System.out.println(popeye.goal()); System.out.println(wesley.getRealGoal()); System.out.println(popeye.getRealGoal()); System.out.println(wesley.str); System.out.println(popeye.str); Changes in subclass ONLY affect subclass; Sailor does not gain getRealGoal()
How Does Inheritance Work? Inheritance occurs automatically with extends DO NOT RETYPE INHERITED MEMBERS Redeclaring fields yields bad things that cannot be fixed Some value in overriding methods by redeclaring them
Inheritance Key Concept #3 Automatically inherit fields & methods: Can override methods; NEVER redeclare fields
Overriding Methods In code, can redeclare inherited method in subclass "Overloaded" if different signature used in subclass Method said to be "overridden" if signatures identical If subclass method different, then okay to override Method changed only for subclass & its subclasses Original used by superclass & other classes, however Method depends on this - instance specifies definition
Overriding Methods Within override, can call method in superclass Only while overriding method – cannot call elsewhere Allows reusing inherited method as part of new method super.methodName(…) to call method Chaining illegal super.super.methodName(…) Cannot make less accessible when overriding However, method can make more accessible
Overriding Methods Within override, can call method in superclass Only while overriding method – cannot call elsewhere Allows reusing inherited method as part of new method super.methodName(…) to call method Chaining illegal super.super.methodName(…) Cannot make less accessible when overriding However, method can make more accessible
Delegation Key Concept Image of Homer Simpson used under Parody & Fair Use exceptions. Original from: http://www.ebay.com/blogs/stories/cant-someone-else-just-do-it
Composition Key Concept #1 When relationship between classes is Has a(n): Add fields & Delegate actions
Inheritance Key Concept #1 When relationship between classes is Is A(n): Use extends
Inheritance Key Concept #2 Every Java class extends exactly 1 class
Inheritance Key Concept #2 Every Java class extends 1 class directly and can inherit from many others via superclass
For Next Lecture Read 1.4 - 1.6 for Friday and be ready to discuss What is polymorphism? Why would chains be important in CSE? Is there ever a reason to add a typecast? As usual, the weekly assignment due next week Due by 12:45PM Monday using AutoLab