Anatomy of an object and encapsulation Flashcards Preview

Object Oriented Programming in Java > Anatomy of an object and encapsulation > Flashcards

Flashcards in Anatomy of an object and encapsulation Deck (30)
Loading 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) { = 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 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?


* 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


* 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 "" that would have a main method. When you run that class it would reference a separate file like "" 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()) {


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 accessoryList = new ArrayList();

These accessories might even be objects themselves, defined in; if so, the field would look like:

ArrayList accessoryList = new ArrayList();

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) {



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;



What is the syntax for writing a constructor?

In your object class you can specify what happens when your client calls the "new" keyword by adding a special type of method, the constructor. Here is what the constructor looks like for our Bicycle class:

public Bicycle (String myBrand, String myModel, double myPrice) {

this.brand = myBrand;

this.model = myModel;

this.price = myPrice;


As you can see there are a couple things in the constructor header that are different from typical methods:

* The name of the method is the class name "Bicycle"

* There is no return type (void, int, etc.) specified for the method, because a constructor will always return an object of its own class. If you specify a return type by mistake, even void, you will have a standard method, not a constructor and the client call above won’t work.

The general format for a constructor header looks like this: public ClassName (parameters) {

Since the constructor is called when creating a new instance of an object you will want to do any work to set up the object for use by the client. Often this means initializing the fields. If we want the user to be able to specify the initial values for the fields, we need parameters that match the fields.

public class Bicycle {

String brand;

String model;

double price;

boolean isSold;

double salePrice;

public Bicycle (String myBrand, String myModel, double myPrice) {

brand = myBrand;

model = myModel;

price = myPrice;

isSold = false;

salePrice = 0.0;




  1. This constructor only accepts the value of three fields from the client; the other fields are set to defaults.
  2. Because we set all the fields values within the constructor we no longer need to set their values at their declaration. This approach of splitting declaration and initialization is the preferred style.
  3. We used different names for the parameters than the fields, but because they store the same type of data it’s really tempting to write:

public Bicycle (String brand, String model, double price) {

brand = brand;

model = model;

price = price;


But, this will NOT set the values of the fields! Remember that parameters create local variables of the same name in the scope of a method, and that variable will "mask" the field of the same name in this method, so brand = brand uselessly sets itself to its own value. Oops!

Java does permit you to explicitly qualify that you want the object to refer to its own field by using the keyword this. You could write the constructor using the field names as parameter names as long as you distinguish the difference with the "this" keyword:

public Bicycle (String brand, String model, double price) {

this.brand = brand;

this.model = model;

this.price = Price;



What happens if you don't provide a constructor for an object?

You do not have to provide a constructor for an object at all. If you don’t, Java provides a default for you known as the zero argument constructor. In the case of our Bicycle class it would look like this:

public Bicycle() {


If you do not specify a constructor yourself, then when the client class creates a new object it cannot pass in any arguments. This means that the fields will initially store their default values:

Bicycle bike1 = new Bicycle();


What is the benefit of overloading constructors?

You can in fact have as many constructors as you like through overloading. In this way you can allow users to decide what amount of data they want to specify when creating and object, and what amount they want to rely on default values.

To do this properly you should first create a constructor that initializes all fields inside the constructor:

public class Bicycle {

String brand;

String model;

double price;

int tireSize;

boolean isSold;

double salePrice;

public Bicycle (String brand, String model, double price, boolean isSold, double salePrice) {

this.brand = brand;

this.model = model;

this.price = price;

this.isSold = isSold;

this.salePrice = salePrice;



As you can see we have moved all the field declarations within the constructor, giving the user complete control over the initial state of the object. Now that this constructor exists you can add other constructors that include default values so your user doesn't have to set everything. You can call the most specific constructor from the less specific constructors to reduce redundancy. You call one constructor from the other with the use of the "this" keyword in the place a method name would normally be.

If some bikes don’t have a model, for example, you could provide:

// this uses the default values of 28 for the tireSize

// false for isSold and set the salePrice to the listPrice

public Bicycle(String brand, String model, double listPrice) {

this(brand, model, listPrice, 28, false, listPrice);


// this uses all default values for a new Bicycle

public Bicycle() {

this("", "", 0.0, 28, false, 0.0);


Now we can create new Bicycles in our client class with differing levels of initial information like so:

Bicycle specificBike = new Bicycle("Giant","OCR-1",899.99,28,false,599.99);

Bicycle genericBike = new Bicycle("Schwin","Cruiser",250.00);

Bicycle defaultBike = new Bicycle();



What is abstraction?

Abstraction is a concept that separates how to use something from the details of how it’s implemented. For example: You can press the brake pedal of a car and stop effectively without knowing anything about disc brakes, calipers, hydraulics, or frictional coefficients


What is encapsulation?

Encapsulation allows you to strictly control how a user interacts with your object. By hiding all the inner workings of your object from the user you can guarantee that your object stays in a good state.

Just imagine if you didn't have a brake pedal and everyone driving was expected to know how to apply pressure to the disk breaks, chances are a lot of people would ruin their cars! By hiding the inner workings of the car with the casing and providing a clear way to interact with the brakes (the pedal) you help keep the car in working order.


How are the keywords "public" and "private" used to encapsulate an object?

Instead of making everything "public" a well encapsulated object only exposes those things that a client needs to use the object effectively, making everything else "private". This is how you prevent a user from accessing things they are not supposed to use. Obviously, some things must be public or no one could use the object! But now by using "private" and "public" intentionally you can decide exactly how external code should interact with your object.


Why should object fields be set to private?

public class MyClass() {

private String field1;

private int field2;

private double field3;


As they store the foundational information about your object fields should generally all be made private. This way you can use them like normal variables within your class, but your client code cannot change their values directly. This can protect the inner state of your object from being corrupted. If you want your client code to know the current value of a field, you'll want to write separate public methods that limit the way a user interacts with your fields. That way you can protect your object in several ways:

* Restrict the value of fields to a range of valid values (maximum speed, minimum price, only certain values, etc.)

* Make sure that values of different fields remain consistent.

* Prevent clients from making assumptions about field values that you may not have intended.


Why would you make a method private from within the class in which it is defined?

private void myMethod() {

When a method is declared as "private" it means you can only call that method from within the class in which it is defined. Usually, methods are public unless they are an internal "helper" method that is used by other public methods. These private methods can help you remove redundancy and clean up your own work. They are not for external users to have access to behavior, but rather a way for you to internally structure your own code. Let's say we are writing methods for our Student class, and we find that we keep repeating the check to see if they are eligible to graduate. This is a check you might have to do often, but is such an important state you might not want external code to be able to perform that update. If you make a private method you can call it within your class to eliminate redundancy, but you protect your Student state from being updated by a client class.

private boolean updateGrad(double gpaUpdate, int attendanceUpdate) {

gpa = (gpa + gpaUpdate) / 2;

daysAbsent += attendanceUpdate;

canGraduate = (gpa >= 2.0) &amp;&amp; daysAbsent < 10;



Why would make a constructor private?

private MyClass() {

Rarely will you want to make a constructor private, as the constructor is what enables your user to even create an instance of your object. However, if you are overloading constructors and you are using a constructor that sets each individual field to eliminate redundancy you might want to make it private and only expose the constructors that take the correct parameters for your user.

private String name;

private double gpa;

private int daysAbsent;

private boolean canGraduate;

private Student(String name, double gpa, int daysAbsent, boolean canGraduate) { = name;

this.gpa = gpa;

this.daysAbsent = daysAbsent;

this.canGraduate = canGraduate;


/* Create a new student at the beginning of the school year */ public Student(String name) {

this(name, 4.0, 0, true);


/* Create a new student joining later in the school year */

public Student(String name, int daysAbsent) {

this(name, 4.0, daysAbsent, true);



How can one access private elements of an object?

When you make a code element "private" you can use it within the class in which it is defined, but not in any client code or other object definitions. However, you can access private elements of other objects of the same type.

/* this method works even though the other Student's fields are marked as private */

public boolean equal(Student other) {

return && this.gpa == other.gpa && this.daysAbsent == other.daysAbsent;



What is an accessor method?

Accessors are a type of method that exposes the current value of your field to external code. You can think of these as a "read only" method for your field's values. Often they are referred to as "getters" because typically their names are getFieldName() like so:

public double getGpa() {

return gpa;


It's common for you to have an accessor method for each of your fields. They typically do not take in any parameters and simply return the current value of the field they are accessing.


What is a mutator method?

Mutators are a type of method that allows external code to change the value of a field. This is a lot of responsibility, so often you will want to add logic to these methods to maintain a good state for your fields.

/* allows the user to change a student's name, accepts all types of capitalization. Names cannot contain spaces */

public void setName(String name) {

if (name.indexOf(" ") != -1) {

throw new IllegalArgumentException("names cannot contain spaces");

} = name.toLowerCase();


Mutator methods typically take in a parameter and change the value of a field after doing some checks to see if it is an appropriate value.


What does the "static" in front of methods do?

Static simply means "not part of an object", or "not dynamically created" as part of an object when the object is created.


Why would you make a field "static"?

public class MyClass{

private String field1;

private static int field2;


When a field is static it is shared by all objects in a class. Sometimes it’s referred to as "a class variable". This means each individual instance of that object can all read the field's value and update it. There is only one instance of this field across all instances of the object so the static field's current value is the last value set by any object. This can be really handy for:

* Accumulating statistics or totals for all members of class: total sales for all vendor objects, the number of Bicycle objects created, etc.

public class Bicycle {

private static int bikeCount;

public Bicycle() {

bikeCount++; // stores the count of how many Bicycle objects have been created



* Shared values that all objects of a class use: current speed limit, value for gravity, and other values that might change but need to affect all objects.

public class DriversLicense {

private static int minDrivingAge = 21;

public void newLaw(int newDrivingAge) {

minDrivingAge = newDrivingAge;



Static fields belong to the class as a whole, not to a specific object of the class. So, if you reference it outside the class, you use the class name to qualify it, not an object name: for example, Bicycle.numberOfBikes, Vendor.totalSales, etc.

Bicycle bike1 = new Bicycle();

Bicycle bike2 = new Bicycle();

int bikeCount = Bicycle.bikeCount; // should store 2

The class constants we saw before are simply class variables that are also final and so can never change. When they are public, they are usually "universal constants" like Math.PI or Color.BLUE.

Static fields behave differently from the typical instance fields.


What is the function of "static" methods?

Like static fields are shared across all instances of an object, so are static methods. This means that in any class, a static method is part of the class as a whole:

  • The main method that starts a Java program is always static. It usually creates the first objects. There is only one main method for each execution of a Java program.
  • From within a static method you cannot call a non-static method without specifying which instance that method belongs to; for example, bike1.getBrand(), or vendor1.addSale().
  • When a static method exists within an object declaration it’s often a "public service" method. This is often something that doesn’t deal with any objects at all, but just acts on data provided as parameters or static variables. For example, whenever we use methods from the Math class: Math.pow(2,2).