UNC COMP 301 - F26/Lec 3 - Motivating OO; Encapsulation; Assn 01; Interfaces
Overview
Muhammad Sayeed Ghani develops the Java triangle-area example from static functions and six coordinates into Triangle and Point objects, then explains how encapsulation, immutability, and nonredundant representations prevent design and aliasing problems. He also previews Assignment 1’s reflection API and constructor chaining, and shows how Java interfaces let code switch implementations, such as Cartesian and polar points, without changing client code.
Key takeaways
- Triangle area and category belong as instance methods because they operate on one Triangle's state, while a general distance calculation belongs on Point or remains a static helper because it needs two points.
- Sharing mutable Point references between Triangle objects can create aliasing bugs: shifting three points in one triangle can distort another triangle that shares two of them.
- Immutable objects avoid those side effects by returning new objects for operations such as translation instead of changing existing coordinates.
- Minimal representations reduce inconsistency: an axis-aligned square can use one corner and a side length, while area can be derived rather than stored redundantly.
- Programming to a Java interface such as Point decouples client code from CartesianPoint or PolarPoint implementations and permits different representations in one Triangle.
- Java constructor chaining uses this(...) as the first statement to reuse overloaded constructors, while reflection can inspect private members but should be limited to specialized uses such as testing.
Chapters
- Ghani resumes the triangle-area application, which began as a non-object-oriented program and is being refactored into Java classes.
- The session plans to cover encapsulation, selected Assignment 1 details, and interfaces.
- Lecture code is available in Canvas; office hours use room SN1 136 and CSXL.
- An object's state is determined by the current values of its fields.
- The earlier Triangle refactor introduced a class, fields, and a constructor, and distinguished constructors from ordinary methods.
- When a local variable or parameter shares a field's name, Java resolves the local name first, then the instance field; otherwise the name is undefined.
- Triangle area and category depend on one particular triangle, so they fit naturally as instance methods in Triangle.
- After the move, callers invoke the methods on a Triangle object and need not pass its six coordinates again.
- Point distance still needs two coordinate pairs, so it is not inherently an instance operation on a triangle with three possible sides.
- Replace Triangle's six separate coordinate fields with three Point objects, each combining an x and y coordinate.
- Move distance calculation to Point as an instance method such as distanceTo, which uses the current point and accepts one other point.
- A static point-distance helper can remain inside Triangle when it serves as an internal utility for calculating side lengths.
- Java static fields and methods belong to the class and can be accessed through the class name.
- Define the triangle side-comparison tolerance as a named constant such as SIDE_EPSILON using static final.
- Comparing double values within an epsilon avoids treating tiny rounding differences as meaningful inequality.
- Encapsulation, also called information hiding, protects internal data and controls what users of a class can access.
- Private fields prevent client code from changing an object's representation directly, allowing an implementation to change from Cartesian to polar coordinates.
- Interfaces define public behavior as a contract, letting implementation code change while keeping external code and tests stable.
- Protected access includes subclasses, potentially across packages; default access is more restrictive because it is limited to the package.
- Two Triangle objects share points P2 and P3, so changing coordinates through Triangle 1 also changes the points used by Triangle 2.
- Translating Triangle 1 by adding 5 to each x coordinate leaves its perimeter unchanged but distorts Triangle 2 and changes its perimeter from about 63 to 70.
- The unexpected side effect is an aliasing bug: separate references point to the same mutable Point objects.
- Constructing each triangle with fresh Point objects avoids shared references, as confirmed by the second example's unchanged perimeters.
- Making Point and Triangle state private and final prevents clients from modifying coordinates directly, though immutability requires avoiding mutable state changes.
- Implement translation by creating and returning a new Point or Triangle instead of changing the original object.
- This approach resembles Java String behavior and prevents changes through one reference from unexpectedly affecting another object.
- A square aligned with the x and y axes can be represented by a top-left Point and one side length instead of four corner points.
- A rotated square needs additional orientation information, such as two opposite corners or a point, side length, and angle.
- Redundant fields such as both side length and area can disagree after an update, creating data-integrity problems similar to inconsistent database records.
- Caching a derived value can still be worthwhile when its calculation is expensive and the program accesses it frequently.
- Java naming conventions use get and set prefixes with lower camel case, as in getSide and setSide.
- A square's top-right corner can be computed from its top-left point and side length rather than stored as another field.
- A setter should validate inputs such as requiring a positive side length.
- For invalid values, code can report an error or throw IllegalArgumentException with a message and failure location.
- Java reflection can inspect private fields and methods, bypassing ordinary encapsulation; Assignment 1 uses it, but routine application code should avoid it.
- Reflection can support testing by checking whether a class exists and listing its fields or methods, including private members.
- Constructor chaining uses this(...) to call an overloaded constructor, such as a Player constructor supplying a default health of 100.
- A this(...) constructor call must be the constructor's first statement, and one constructor cannot make two such calls.
- An interface declares method signatures, including names, parameters, and return types; implementing classes must provide the required public methods.
- A Java class can implement multiple interfaces, allowing it to meet more than one behavioral contract.
- The Point interface specifies operations such as coordinate access and distance calculation, while CartesianPoint supplies one concrete representation.
- An interface name can describe the abstraction, with a concrete class name such as CartesianPoint identifying the implementation.
- Declare a variable using the abstraction, such as Point p = new CartesianPoint(...), rather than tying the variable type to CartesianPoint.
- A PolarPoint implementation can derive x and y from radius and angle using cosine and sine while preserving the Point contract.
- A Triangle that stores Point references can combine CartesianPoint and PolarPoint objects without requiring Triangle code to know their representations.
- If Triangle instead requires CartesianPoint for every vertex, supplying a PolarPoint creates a compile-time type error and blocks implementation changes.
Transcript excerpt
0:01 Right. Good afternoon everyone. So, first of all, I'd like to apologize for uh Tuesday. Uh that hasn't happened too many times in my career, but does happen once in a while. Um apologies for any inconvenience. Um now, in terms of making up that session, um we'll see how it goes. So far it seems like um we are moving fairly somewhat ahead of the schedule. So hopefully that may not be required but we'll see. So [clears throat] let's pick up from where we left off in last last week where we were talking about uh motivating ourselves towards an object-oriented paradigm and we looked at the triangle area application which
0:49 we started off by uh looking at a completely non-object-oriented implementation and in the last lecture uh we sort of went went midway towards converting that into an object-oriented uh implementation and today hopefully we'll complete the entire process which also involves uh encapsulation. So we'll take a look at that. Um the code for last week as well as for today has been uploaded in canvas. Um as far as encapsulation is concerned, we're going to start off by looking at principles of encapsulation, look at some examples and then uh towards the end of that we will take a look at a quick look at assignment one and uh just
1:38 a couple of pointers uh some aspects of assignment one which are somewhat unique and new. So we'll take a look at those and then finish off by taking a look at interfaces. So interfaces are also somewhat um shouldn't be new for you. Um however there are some aspects of it which will be new. Okay. So um we do have um we have started office hours as you might have noticed. Uh we do have a couple of new
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Muhammad Sayeed Ghani.