Anatomy of an object and encapsulation Flashcards
What is the difference between “procedural programming” and “object oriented programming”?
Procedural programming involves code that always executes based on the main method, moving from top to bottom
Object oriented programming involves defining new entities in Java that can interact with one another
Why use objects in programming?
Creating objects lets you organize your code into more modular units, which can be extremely useful when writing large amounts of code.
For example, let’s say you are trying to write a program to manage student information.
String stu1Name = “Ada Lovelace”;
int stu1Grad = 2017;
int stu1ID = 12345;
double stu1GPA = 3.2;
int stu1Abs = 4;
String stu2Name = “Alan Turing”;
int stu2Grad = 2016;
int stu2ID = 12346;
double stu2GPA = 3.8;
int stu2Abs = 9;
String stu3Name = “Margret Hamilton”;
int stu3Grad = 2017;
int stu3ID = 12347;
double stu3GPA = 3.92;
int stu3Abs = 0;
As you can see, this can get pretty unmanageable very quickly. When you create your own object, you can formally group this data together under a brand new Data Type. This way all this information can be stored under a single variable!
public class WhosGraduating {
public static void main (String[] args) {
Student ada = new Student(“Ada Lovelace”, 2017, 12345, 3.2, 4);
Student alan = new Student(“Alan Turing”, 2016, 12346, 3.8, 9);
Student margret = new Student(“Margret Hamilton”, 2017, 12347, 3.92, 0);
}
}
What is the syntax for “defining” a new object class?
In order to create a new object you have to write a class that “defines” it. In this way you can think of this as adding a new keyword to Java, but to do so you have to tell Java what this keyword means. Here’s how we would define a “Student” object that includes all the variables from the example above:
public class Student {
String name;
int grad;
int ID;
double GPA;
int abs;
public Student(String name, int grad, int ID, double GPA, int abs) {
this. name = name;
this. grad = grad;
this. ID = ID;
this. GPA = GPA;
this. abs = abs;
}
public boolean isGraduating() {
return (GPA > 2.0 && abs < 10 && grad == 12);
}
}
Notice that this class does not have a main method. That is because this code cannot be executed by itself, but must instead be invoked by a different class that does have a main method.
Objects often model objects in the real world and their characteristics can help us design them. For example, a bike shop might define their Bicycle object to include data like its brand name, model name, list price, tire size, number of gears, whether it has been sold or not, the sales price, and more. The shop might need to do things like change the Bicycle’s price when there’s a sale, mark it as sold and more.
This definition of a Bicycle object is contained within a class, just like all the code we’ve been writing. However, this is a special class that tells Java how to create individual occurrences or “instances” of your design. In our Bike Shope example each instance of “Bicycle” would represent a real bike in the shop. Our definition acts as a “blue print” dictating what data and behavior each Bicycle should have, then we can create different instances of Bicycles each with its own values for the data we defined.
Once we have defined what a Bicycle object should look like in Bicycle.java then we can create individual copies of Bicycles like we have been doing with the objects we already use:
Bicycle bike1 = new Bicycle();
What is the difference between an object class definition and an object instance?
CLASS
* Defined in Object class
* Specifies types of “attributes” that all objects of this type have * Specifies “behaviors” of its objects in methods that all objects of this type have
* Java program can contain multiple different Object definitions
OBJECT (INSTANCE)
* Created when program runs using “new” operator
* Holds individual values of attributes that can change as program runs
* Executes behavior on its personal set of attribute values
* When a Java program is run it can create as many different copies of each Object that is defined
How do you create an object in a client class?
Within a client class you might create objects. This is what happens when you create a “new ArrayList” or a “new Scanner”. In this case “ArrayList” and “Scanner” are examples of object classes that define what these objects store and can do. When you create new instances of these objects in the client class you can fill them with data and use their methods to ask them to do things.
Here’s how a client class creates three new Bicycle objects each with their own brand name, model name, list price, and wheel size:
public class BikeStore {
public static void main(String[] args) {
Bicycle bike1 = new Bicycle(“Giant”,”OCR-1”,899.99,28);
Bicycle bike2 = new Bicycle(“Specialized”,”Dolce”,1399.99,30);
Bicycle bike3 = new Bicycle(“Schwinn”,”Cruiser”,299.99,24);
}
}
Each of these three variables are an instance of a new Bicycle object, each with its own data.
This code would be contained within a client class with a name like “BikeManager.java” that would have a main method. When you run that class it would reference a separate file like “Bicycle.java” that contains the object definition for “Bicycle” to know how to create these three variables.
What is the syntax for manipulating an object using its own methods?
To ask an object to do things using its methods, you use the name of the specific object to “qualify” the method name. Then pass in any necessary parameters and use its return value (if any) as usual:
if (!bike1.isSold()) {
bike1.setSold();
Manual m = bike1.getManual();
}
These two method only refer to the inner state of the bike1 variable, but leave the bike2 and bike3 object instances untouched.
The code for these methods exist in the object definition, but they are executed in the client.
You’ll probably recognize this syntax for calling methods from when we used it with String variables:
String name = “Theodore”;
if (name.length() > 0) {
name = name.toUpperCase();
String nickName = name.substring(0, 4);
int length = nickName.length();
}
As you can see, you use the name of the specific object variable to call the method on that instance, like so:
ObjectDataType variableName = new ObjectDataType(); variableName.objectMethod();
In general, objects are compose of what three parts?
In Java, objects are composed of three distinct parts. In your Java class, they are usually organized like this:
What is the state of an object?
The state of an object is defined by the collection of instance variables who’s scope is that of the entire object. We call these “fields”. This collection of variables holds all the data associated with an object instance. Together, they represent the state of an object, everything that distinguishes it from other objects of the same type, or from itself at different points in time. If you created another object with exactly the same state, it would behave identically, but still be considered a separate object. That is because each time you make a new object you create a space for it in memory, so even if that memory stores the same values they are still distinct allocations of data.
What are the constructors of objects?
Constructors are a special type of method that is invoked by the “new” operator. This is what creates and initialize instances of the object and typically sets the initial value for all the fields.
What is the behavior of an object?
The behavior of an object is dictated by what methods you define in the object class. These methods represent the things a client class can do with an objects of this type. These methods typically modify the state, but they can also interact other classes or with the user like a Scanner or a PrintStream does. (System.out is actually an object of the PrintStream class.)
What is the syntax for defining a field of an object?
You define fields the same way define any other variable, but you define them outside of a method, traditionally right after the class header.
public class MyObject {
String field1 = “”;
int field2 = 0;
double field3 = 0.0;
…
}
By defining the fields outside any method that gives them the scope of the entire class. This means that they can be used by any method within the class, so you should try to limit them to those values that are strictly necessary.
You need to determine what Java data type to use and they can be a primitive data types, or any type of object including other classes that you have defined. Here’s what our Bicycle object might have:
public class Bicycle {
String brand = “”;
String model = “”;
double listPrice = 0.0;
int tireSize = 24;
boolean isSold = false;
double salePrice = 0.0;
…
These are the aspects of a bicycle that are most important for the shop owner, so they are created as fields.
Fields can be objects as well. For example, you could create a list of all the different accessories that come installed on the bike:
ArrayList<string> accessoryList = new ArrayList<string>();</string></string>
These accessories might even be objects themselves, defined in Accessory.java; if so, the field would look like:
ArrayList<accessory> accessoryList = new ArrayList<accessory>();</accessory></accessory>
As shown, the naming convention for fields is to use nouns in camelCase.
What is the syntax for using a field within an object’s code?
Once you’ve created a field it works just like any other variable. You refer to it by name whenever you need to use it within your object’s code.
public class Bicycle {
double listPrice = 899.99;
double salePrice = 599.99;
// Updates the price of the bicycle to be the // reduced sale price
public void setSale() {
listPrice = salePrice;
}
}
You can also access an object instance’s fields from the client class using the name of the variable like so:
public class BicycleManager {
public static void main(String[] args) {
Bicycle myBike = new Bicycle();
myBike.listPrice = 1000.00;
}
}
However keep in mind that directly accessing the fields from the client code is not considered good style. We will talk about how to improve this in the encapsulation section.
When would you use the “this” keyword?
Sometimes it can get confusing between what parameters are inside your class and which are being passed in from an external source. To help make this more clear you can add the “this” keyword in front of your object fields. For example, you might have a method that takes in a parameter from the client that you want to save into the value of your field. You can use the this keyword to make it easier to distinguish between the parameter and the field.
public void setPrice(double newPrice) {
this.listPrice = newPrice;
}
What is the syntax for writing a method for an object?
You write methods for an object the same way you’ve written other methods, except you omit the static property.
public returnType methodName(parameters) {
statements;
}
You will want to define your methods after your fields within your class, like so:
public class MyClass {
String field1 = “”;
int field2 = 0;
public void updateField(int param) {
field2 = param;
}
}
The job of these methods is to execute some action, so often they will have names that begin with verbs like “get”, “set”, “calculate” etc…
As this work is typically performed on the fields, you will usually want to combine your verb with which field this method acts upon.
Let’s look at our Bicycle example. Our Bicycle field has the following fields:
public class Bicycle {
String brand = “”;
String model = “”;
double listPrice = 0.0;
int tireSize = 24;
boolean isSold = false;
double salePrice = 0.0;
…
This Bicycle class is intended to be used by a shop keeper who sells Bicycles, so some things they might want to do are:
// returns a String with basic information about
// the bicycle
public String getInfo() {
return brand + “ “ + model + “ $” + price;
}
// marks the bicycle as sold and returns
// the asking price for the customer
public double makeFullPriceSale() {
isSold = true;
return listPrice;
}
// marks the bicycle as sold and returns
// the asking price for the customer
// during a sale
public double makeReducedPriceSale() {
isSold = true;
return salePrice;
}
As you can see we can create behaviors based on what a user might want to be able to do with the fields.
Can an object’s methods access the field in other objects of the same type? If so, how?
Your object’s methods can access the field in other objects of the same type. For example, in our Bicycle object we could implement an equals method that determines whether two Bicycle objects have the same brand and model like so:
public boolean equals(Bicycle other) {
return brand.equals(other.brand) && model.equals(other.model);
}
This is another case where the “this” keyword could help make things more clear. The above method could be rewritten:
public boolean equals(Bicycle other) {
return this.brand.equals(other.brand) && this.model.equals(other.model);
}
The client code would use this method on two separate Bicycle variables, like so:
Bicycle bike1 = new Bicycle(“Schwinn”, “Cruiser”);
Bicycle bike2 = new Bicycle(“Giant”, “Racer”);
if (bike1.equals(bike2)) { // in this case would return false
bike2.listPrice = bike1.listPrice;
}