---------------------------------------------- Lecture overview: - Extending a class ---------------------------------------------- A basic class public class Point{ int x; int y; public Point(){ x = 0; y = 0; } public int getX(){return x;} public int getY(){return y;} public void setX(int x){this.x = x;} public void setY(int y){this.y = y;} } What if there might are some colored points in the system. - just add color as a field to Point and mutators and accessors for color * Show them the code Q: What is wrong with this approach? - points that don't have colors also have these fields - from a performance point of view, more memory allocation, unused memory regions - difficult to understand code, because color is not being used for those points - just add another type ColoredPoint in the system * Show them the code Q: What is wrong with this approach? - ColoredPoint are points too, but we may not be able to use our new class ColoredPoint as such - ColoredPoint essentially replicates the functionality of ordinary points, i.e. no reuse. - have class ColoredPoint inherit from class Point - essentially reuse all the functionality of Point * Show them the code ------------------------------------------------------ CONSTRUCTORS in INHERITANCE RELATIONSHIPS ------------------------------------------------------ Q: Does ColoredPoint know how to construct Point? - Use super * Show the the code Exercise: What happens if you don't explicitly call super() or this() as the first statement in your constructor? Construction order - Super class cosntructor - Field initializer and initialization block - body of the constructor ------------------------------------------------------------- INHERITING AND REDEFINING ------------------------------------------------------------- Let's add a distance function to the class Point. * Show them the code double distance(Point other){ return Math.sqrt((this.x - other.x) * (this.x - other.x) + (this.y - other.y) * (this.y - other.y)); } Now let's define a three-dimensional point Point3D. * Show them the code - inherits from Point, adds z, mutator, accessor, etc What about distance? - clearly not the right behavior - how can we fix? > define a new implementation of distance in Point3D *show them the code Exercise: Can we change method signature while overriding? Exercise: Can we change method return type? (Special cases) Exercise: Can we change access modifiers for overriden methods? OVERLOADING: Let's add a moveBy function to the Point - moves the point by (dx, dy) *show them the code What would be a corresponding implementation of moveBy function for Point3D? * show them the code How is it different from moveBy for Point? but they have the same name. (Overloading) How are fields hidden?