Unit 8 Comp Sci Quiz
How does Encapsulation facilitate changes to the internal implementation of a class?
The beauty of encapsulation is that the "expert" developer of a class can change the internal implementation of the class without changing the public interface of the class. When such a change is made, the "non-expert" user of the class need not change any of his or her code, but only needs to recompile his or her code with the new version of this class. The example in the book on page 566-567 shows how the internal implementation of the TimeSpan class was changed from public class TimeSpan { private int hours; private int minutes; //constructors and methods not shown } To: public class TimeSpan { private int totalMinutes //constructors and methods not shown } In this example, the internal design change to the TimeSpan class was made without affecting any client code (code written by software developers who are using the TimeSpan class)
Private Implementation of a Class
consists of any private instance fields and private methods of that class. Private instance fields and methods cannot be accessed outside the scope of the class. Examples of the private implementation of the car would be the brakes, the engine, the circuits of the radio, etc.
Accessor
An instance method that provides information about the state of an object without modifying it.
Constructors - what are they and what is their purpose
a constructor is a piece of code that initializes the state (instance fields) of new objects as they are created. We can think of a constructor as a special type of method that creates a new object of that class and returns a reference to that new object.
Factory Analogy for Constructors
we can think of constructors as factories. A default "Car" constructor is a factory which produces "generic" cars for customers who want to modify the car after it has been built, such as add a new radio of custom tire rims. A constructor with parameters is analogous to a factory which produces "custom" cars based on a specific order from a customer, such as "build me a car with a Bose Sound System and 24 inch chrome tire rims".
Using this to write multiple constructors
we can use this to "factor" the code of multiple constructors. Here is an example of two constructors for the point class: public Point(int x, int y) { this.x = x; this.y = y; } Rather than writing the default constructor as follows: public Point() { this.x = 0; this.y = 0; } We can write it more elegantly as follows: public Point() { this(0, 0); } Here the default constructor calls the constructor which takes two int parameters.
toString method
A method that returns a String value which represents the state of the object. If the toString method is not implemented in a class, that class will inherit the implementation from its parent class, ultimately the Object class. Having a toString method enables us to print object references and use object references in String concatenation expressions.
Visualization of an object reference and object
Consider the declaration and initialization of the following object Point p = new Point(3, 8)
3 Operations that occur when a Constructor is executed
Consider the following line of code: Point p = new Point(3, 8); A new Point object of that class is created and allocated in memory. The amount of memory reserved is determined by the instance fields and their types. The Point constructor is called on the newly created object, passing the two integer parameter values to the constructor. The constructor initializes the instance fields of the object. A Point reference variable named p is created and assigned a reference to the newly created object
Encapsulation
Hiding the implementation details of an object from the clients of the object. Encapsulation helps provide a "division of labor" between the expert implementing a class and the non-expert using the class
Y2K Bug - how was is related to encapsulation
In the first 40 years of writing software for computer systems, many different software developers developed many different "private implementations" of dates. Many of these only used two digits to represent year (March 7, 1995 would be represented as an integer 950307. This because a problem when the year 2000 arrived. Because date implementations in computer software were not encapsulated, companies needed to review every single line of code in their computer systems and fix every single case of where dates were used in their computer code. This was a massively expensive and time-consuming process. Had companies created a Date class and represented every date as a Date object, they would have only had to change the implementation of one instance field which represented the year of the date. For many companies, this would have been the difference between changing 2 or 3 lines of code (with the encapsulation you get from a Date class), versus millions of lines of code (without the encapsulation you get from a Date class).
private
Java keyword we can use to encapsulate instance fields (and methods). Private fields are visible to all of the code inside the class, but none of the code outside the class.
Object-Oriented Programming (OOP)
Reasoning about a program a set of objects rather than as a set of actions
Benefits of Encapsulation
The benefit of encapsulation is that the user of a class does not need to know the details of the class' design in order to use it. In the same way, when we drive a car, we don't actually need to know how the engine, brakes or sound system works, we only need to understand the "public interface" of the car (brake pedal, speedometer, accelerator pedal, radio buttons, radio display, etc.) in order to drive it. This also provides a "division of labor" so that an expert on designing brakes, can design the inner workings of brakes, while a designer of the entire car can focus on the design of the entire car without worrying about the inner workings of brakes.
What happens if you write a constructor with parameters, but not default constructor for that class?
The compiler will NOT automatically create a default constructor. The author of the class must write a default constructor if one is desired.
What happens if you do not write a constructor for a class?
The compiler will automatically create a default constructor which initializes instance fields: int's to 0, doubles to 0.0, booleans to false and object types to null
this
a Java keyword that allows you to refer to the implicit parameter inside a class. This is particularly useful when a method take a parameter of the type of the class (e.g. a method in the Point class which takes a Point object as a parameter)
Invariant
a condition that can be relied upon to be true during execution of a program, or during some portion of it.
Default Constructor
a constructor which does not take any parameters.
Instance Methods
a method inside an object that operates on that object. Specifically it operates on the instance fields of that object. A method that is NOT an instance method would be called a static method. Static methods cannot access instance fields in a class, while instance (non-static) methods can access instance fields in a class. We think of instance methods as "per-object", while we think of static methods as "per-class"
Class
a program entity that represents either A program/module, or A template/blueprint for a new type of objects
Object
a programming entity that contains state (data) and behavior (methods)
Behavior
a set of actions an object can perform, often reporting or modifying its internal state
State
a set of values (internal data) stored in an object
Shadowed variable
a shadowed variable is a local variable or parameter variable that has the same name as an instance fields. Consider the following constructor in which we used the same names for the parameters as we did for the instance fields: public Point(int x, int y) { x = x; y = y; } This constructor does not properly initialize the instance fields x and y, because, in the assignment statement x = x, the Java compiler interprets both the left-hand and right-hand sides of the assignment as referring to the parameter variable not the instance field variable. The instance field variables x and y are not assigned any values by this constructor, so they retain the default value (0) which they were given when the object was constructed. We can resolve this ambiguity with the following change: public Point(int x, int y) { this.x = x; this.y = y; } In this version, this.x refers explicitly to the instance field variable named x and x refers to the parameter variable x. This is a good example of shadowing. Shadowing is a good practice because it lets us use a pretty good variable name, x (representing the x-coordinate of the point), for both the instance field and parameter variable, but let's us be clear about which one we are referring to in our code.
Instance Field/Instance Variable/Attribute
a variable inside an object that makes up part of its internal state. Each object has its own copy of instance fields. However, if a field is declared as static, all objects share that one field.
Syntax Template for Instance Field Declaration
accessModifier type variableName; For example, an instance field on a student object might be: private int gradeLevel; The access modifier can be public, private or protected, but we will almost always define instance fields as private so that they are encapsulated. In contrast, static fields are not "per-instance", but are "per-class" and are initialized as follows: accessModifier static type variableName; For example, an instance field on a student object might be the number of active students. This data is not directly associated with a specific student object, but is associated with the "entire class" of students: private static int numberOfActiveStudents;
Class Invariant
an assertion about an object's state that is true for the lifetime of that object. For example, an assertion about a date object would be that the month instance field must be greater than or equal to 1 and less than or equal to 12 (because there is never a month 0 or month 13)
Mutator
an instance method that modified the object's internal state. In other words, a method that changes the value of an instance field. A class with no mutators is called an "immutable class". The Java String class is an example of an immutable class. The designers of Java made String immutable so that String objects would behave more like primitive types such as int in terms of parameter passing and assignment statements. For example, when we pass pass a String variable as a parameter, we are passing a reference to a String object, but because the called method cannot call a mutator on that String reference, it cannot change the String referred to in the calling method.
Record/Struct
an object that contains state but no behavior. For example, in the C programming language, you cannot declare a class, because it is not an object-oriented programming language, but you can declare a struct, which is essentially a group of fields that represent an object.
Instance
another name for an object. We say that an object is an "instance of" its class.
Client
code that interacts with a class or objects of that class
Common error: redeclaring fields in a constructor
consider the following constructor. public Point(int initX, int initY) { int x = initX; int y = initY; } This constructor does not properly initialize the instance fields x and y, because it is declaring local variables x and y and assigning them the values of the parameters. These local variables disappear when the constructor ends because they have local scope. The instance fields x and y are not assigned any values by this constructor, so they retain the default value (0) which they were given when the object was constructed.
Public Interface of a Class
consists of any public instance fields and public methods of that class (though generally we don't usually declare instance fields as public, we declare them as private instead so as to encapsulate them). Examples of the public interface of a car would be the speedometer (accessor), brake pedal (mutator), radio button (mutator), radio display (accessor)
Abstraction
focusing on essential properties rather than inner details. When we talk about Kanye, Big Sean, Future, we see the "abstraction" of "Rapper"
How is Encapsulation Use in the design of consumer products?
ing Snapchat on your iPhone is a great example. A user of Snapchat need only understand the Snapchat interface, not the inner workings of Snapchat, iOS or the hardware of the iPhone. The developers of Snapchat need only to understand the interface to iOS, not the inner workings of the iPhone hardware. The developers of iOS need only to understand the interface to the iPhone hardware, not the inner workings of that hardware.
Syntax Template for a Class Declaration
public class className { //instance field declarations //constructor declarations //method declarations }
Syntax Template for Constructor with parameters
public className(parameter1Type parameter1Name,...) { //statements which initialize the instance fields }
Common error: putting a return type in a Constructor declaration - Why don't constructors have return types? What are their return types?
public int Point() { Would be an example of this error. Constructors don't have return types because the "return type" of a constructor for the Point class would be the type Point. In other words, we think of a Point constructor "returning" a reference to a Point object.
Implicit Parameter
the object that is referenced during an instance method call. For example, consider the following code which constructs a Point object and calls the translate method on that point Point p = new Point(3, 8); p.translate(2, 4); //p is the implicit parameter The reason that it is called the "lmplicit" Parameter, is that, "behind the scenes", the code p.translate(2, 4); Is actually implemented as something like this Point_translate(p, 2, 4);
Scope of Instance Fields
the scope of an instance field is the entire class. Even if an instance field is declared as private, it can be accessed in any code in the entire class, except in static methods. Instance fields are "born" when an object is constructed and they "die" when the number of variables reference the object becomes zero. The Java Garbage Collector periodically frees the memory associated with objects which have no variables referring to them any longer