designate access and visibility constraints to classes, data, constructors, and methods
designate private visibility of instance variables to encapsulate the attributes of an object
CREATING A CLASS
In Unit 2, we learned how to use classes and objects that are built-in to Java or written by other programmers.
In this unit, you will learn to create your own classes and objects!
A good way of thinking about a class is as a "blueprint" or instructions for creating an object.
Analogy: You could think of a class like a cookie cutter that can be used to make as many objects (cookies) as you want.
I know it has been a while, but remember that a class in programming defines a new abstract data type.
So we know what the data types, int, double, boolean, and String are, but what if you wanted to create our own a new data type called "Person"?
That would be an example of an abstract data type, and we would then be able to create new Person objects by creating new variables or instances of the Person class data type.
You can have as many objects (or instances) of the class as you want and the objects can have different attributes (instance variables)!
We have already created many objects using the new keyword, for example:
String message = new String("Hello World!");
This String variable named message is also called an object reference.
Now that we have our Person class, we could create new Person objects (multiple instances) with different attributes (instance variables):
Person person1 = new Person("Blake", "blake_d@msvd.net", 5550492);
Person person2 = new Person("Alexis", "alexis_j@msvd.net", 5551910);
Notice that the attributes for the Person objects are their name, email, and phone number.
WRITING A CLASS
To write your own class, you typically start with a class declaration with public then class then the name of the class.
The body of the class is defined within a set of curly braces { }.
To create a new class in Java using Repl.it, you need to click the "add file" button:
1) The name of the file MUST match the name of the class you are creating.
2) The name of the file must have .java as the extension.
Let's keep working on this Person class.
Objects created with classes have attributes (instance variables) and behaviors (methods).
In other words, the instance variables hold the data for objects and are what the objects "know about themselves" whereas the methods code the behaviors or the actions the objects can do.
A class also has constructors which initialize the instance variables when the object is created.
This is what a possible Person class would look like with instance variables (attributes), a constructor, and methods (behaviors):
Now that I have created my Person.java file with the instance variables, constructor, and method, I can head over to the Main.java file to create new Person objects using the new keyword.
Notice that I also am able to call the print() method that is in the Person class file from the main method in the Main.java class file!
Execution always starts in the main method.
When a method like print() is called, we run the code in the print method for that object.
After a method is finished executing, the control returns back to the next line of code in the main method.
INSTANCE VARIABLES
Instance variables hold the data for an object.
They record what an object needs to know to do work in the program.
Instance variables are also called attributes, fields, or properties.
In general and on the exam, instance variables should be declared private.
Think of private as like your diary (only you should have direct access to it).
In this case private means that only the code in the Person class can directly access the instance variable values.
The Person class declares (but doesn't initialize) three private instance variabes: String name, String email, and int phoneNumber.
These are things that you might want to know about a person, are declared at the top of the class and are within the curly braces { } of the Person class.
The methods of the class share the instance variables, they can access and use them to do stuff.
Now that we have created the Person class, we can have many Person objects (instances) created using the class.
Each object will have their own copies of the same instance variables but most likely they have different values stored in them.
DATA ENCAPSULATION
Object-oriented Programming stresses data encapsulation where the data (instance variables) and the code acting on the data (methods) are wrapped together into a single unit and the implementation details are hidden.
This ensures that the data is protected by being kept private.
anything outside the class can only interact with the public methods and therefore cannot interact directly with the private instance variables.
When designing a class, programmers make decisions about what data to make accessible and/or modifiable from an external class.
The private access modifier is used to encapsulate and protect the data from external access.
Private instance variables can only be accessed by methods within the class in which they are defined.
WRITING CONSTRUCTORS
Objects are created in programs by declaring a variable of the class and using the keyword new followed by a call to a constructor.
Constructors set the initial (init) values for the objects instance variables.
It makes sense that they are called constructors, because they "construct" the object and set those initial values.
Here is the constructor that I created for the Person class:
Constructors are usually written after the instance variables and before any methods in a new class file.
They typically start with public and then the name of the class.
Unlike other methods, they do not have a return type, not even void, after the access modifier public.
Constructors can take parameters (specified in the parentheses) for the data which is used to initialize the instance variables.
Classes usually have more than one constructor (usually there are at least 2):
a constructor that takes no parameters (aka, the no-argument constructor) which usually sets default values.
a constructor that takes all the parameters necessary for initializing all the instance variables.
The attributes of an object and their given values at a given time define that object's state.
The constructors initialize the object's state by assigning initial values to the instance variables that the object has as its attributes.
Here are two constructors that could be written for the Person class.
Notice that the first one is the no-argument constructor with nothing in the parentheses and it initializes name, email, and phone number to default values.
Most programmers use empty strings "" as the default value for String variables and 0 as the default value for int and double variables.
METHODS
Methods define what an object can do or the behavior of the object.
Most methods are public which means they can be accessed from outside the class.
Some methods can be marked as private if they are helper methods that are just used internally by other methods in the same class.
Private methods will not be accessible outside of the class.
The private and public keywords determine the external access and visibility of classes, data, constructors, and methods.
Methods typically start with public then a type, then the name of the method followed by parentheses for optional parameters.
The print() method prints out all the data stored for a person object:
Notice that it starts with public then the return type.
The void return type is used to indicate that the method does not return anything back to the main method which could be used by the program.
In other words, this method is a "one and done" kinda method.
After the void keyword it has the method name followed by parentheses for possible parameters.
The body of the method is enclosed in curly brackets { }.
Notice that the method can access and use the instance variables in the class: name, email, and phoneNumber.
These instance variables are shared by all the methods of the class.
CALLING METHODS
There are two steps to using methods, 1) define the method, then 2) call the method.
Defining a method is like "teaching the program how to do something", and calling the method is like "telling the program to do something".
To call a method to do its job, we created objects of the Person class (named person1 and person2) and then used the dot operator (.) to call its public methods, for example person1.print() means to call person1's print method.
OBJECTS AS INSTANCE VARIABLES
Let's kick this lesson up a few notches, shall we?
In all of the examples above, the instance variables are primitive types, but you can have other objects, reference types, as instance variables.
For example, in the following code I created another class named Address and you can see that the Person class now has an Address object named addr as an instance variable and the Address class has String instance variables for street, city, and state.
When you pass object references as parameters to constructors or methods, they become aliases for the original object and can change it.
If a constructor has an object as an instance variable, it can copy the referenced object in the parameter using new and the constructor of the referenced object as seen below so that it does not change the state of the original object.
SUMMARY
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Instance variables define the attributes or data needed for objects, and methods define the behaviors or functions of the object.
Data encapsulation is a technique in which the implementation details of a class are kept hidden from the user. The data is kept private with access only through the public methods that can act on the data in the class.
The keywords public and private affect the access of classes, data, constructors, and methods.
The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
Instance variables are encapsulated by using the private access modifier.
Methods can be public or private, but they are usually private.
Constructors are used to set the initial state of an object, which includes initial values for all instance variables.
When no constructor is written, Java provides a no-argument default constructor, and the instance variables are set to their default values (0 for int and double, null for objects like String).
Constructor parameters are local variables to the constructor and provide data to initialize instance variables.
EVIDENCE
1) Complete the following Google Form. This form must be 100% correct and includes released AP practice questions. To stop working and return later, hit submit! You can "edit your response" and continue where you left off.
2) Create an "Address Book" program making sure to use the skills shown in this lesson. This should be a program that involves the Scanner; allowing the user to add at least one additional address. OPTIONAL: For an added challenge, include a While loop so that users can keep adding names and addresses to their address book until they wish to stop.
3) MC Exam Practice: This lesson has additional practice problems which can be found on the MC Exam Practice page with an answer key! Use ctrl + f to search for different objectives throughout the year. You could look at these questions now, or, save these practice questions for later and use them to review! The choice is yours.