-
Notifications
You must be signed in to change notification settings - Fork 1
Classes and Objects
Up to this point, we've built programs with only 1 class. This class would contain some sort of methods that perform some tasks. Realistically, your program would be composed of many classes that specialize on specific things. Think of this as a car. For a car to work you need an engine, a transmission, some suspension, some wheels, etc, etc... However, all of these things (classes) perform different functions (methods). A transmission won't be able to perform the function of suspension and vice versa.
We'll get more into this through the section.
Simply put, a class is a template for objects. A class defines object properties including a valid range of values, and a default value.
An object has a state in which all of its properties have values that you either explicitly define or that are defined by default settings. In this case, think of the class as a blueprint of what any car is at a basic level - they all have some basic properties(that can vary a little) and basic functions. Objects, in this case, is when we use that blueprint to make an single car, and define the properties/functions of the object.
class Car{
...
}
I.E. - we could have a car class that defines properties, like the color, the number of wheels or the number of doors, and also describes the object's behavior(functions), such as drive, park, and reverse. An object is a member or an "instance" of a class.
class Car{
int number_doors;
String color;
public void drive(){
...
}
public void park(){
...
}
public void reverse(){
...
}
}
We know that for any variable , we can define the type and name of the variable as such : type name;
We can do the same with classes and thus create objects.
class Box{
int height;
int width;
public void printArea(){
...
}
}
class Main{
Box box = new Box(); //Based on the class we created , we just instantiated a new 'Box' object
}
HOWEVER, there are some MAJOR points we have to touch up on before continuing.
Encapsulation simply means binding object state(fields) and behavior(methods) together. When we create a class, we are indirectly encapsulating the the properties and methods together.
The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.
class Car{
int number_doors;
String color;
}
What does this mean? When an object is instantiated, we only want the user to be able to access methods/properties we deem fit to use.
class Car{
private int number_doors; //these properties of the Car object cannot be accessed outside of the class
private String color;
}
class Main{
Car car = new Car();
car.number_doors = 2; //THIS IS INVALID
}
So How do we Encapsulate?
- Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
- Have getter and setter methods in the class to set and get the values of the fields.
class Car{
private int num_doors; //these properties of the Car object cannot be accessed outside of the class
private String color;
public void setColor(String c){
this.color = c; // the class's 'color' property will now be equal to the value passed in
}
public void setNumDoors(int n){
this.num_doors = n;
}
public void printDetails(){
System.out.println(this.color + " , "+ this.num_doors)
}
}
class Main{
Car car1 = new Car();
car1.number_doors = 2; //THIS IS INVALID. INSTEAD,
car1.setNumDoors(2); // This works
car1.setColor('Green');
Car car2 = new Car();
car2.setNumDoors(4);
car2.setColor('Black');
car1.printDetails();
car2.printDetails();
}
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Think of them as getters and setters for properties, but they occur right when an object is defined/instantiated.
class Car{
private int num_doors; //these properties of the Car object cannot be accessed outside of the class
private String color;
public Car(int n, String c){
num_doors = n;
color = c;
}
public void printDetails(){
System.out.println(this.color + " , "+ this.num_doors)
}
}
class Main{
Car car1 = new Car(2, 'Green');
Car car2 = new Car(4, 'Black');
car1.printDetails();
car2.printDetails();
}
Static in Java can refer to several things, however here we shall talk about the two most important instance of when the static key word is used, a static variable and a static method.
Before moving on we should first explain the concept of what static does. Static is used for memory efficiency as anything that is declared static will be declared only once in the memory space. Or in others, any thing that is static will only have one instance of it.
Let's look at what a static variable does. A variable that is declared static will be shared by other objects that also share a similar variable. For example let us look at a object called 'Student'. Student object may have variables that contain different values. Such as name, age, or address. However each student may also have a variable that is the same for everyone, such as the school they go to. In such case, rather than waste memory by allocating a separate space for individual school they attend, it would be better to allocate just one space for the school they attend to.
For example:
class Student{
int age;
String name;
Static String school = "CPP";
}
If a object of the above class is created, each student object may have a different age and name variable, BUT, all student objects will have the same school variable that points to the same memory.
The other use of static that is commonly used is static methods. A static method can be used even without a object being instantiated. Furthermore a static method can change the value of a static variable.
For example:
class Student{
int age;
String name;
Static String school = "CPP";
static void changeSchool(){
school = "Harvard';
}
}
class main(){
.
.
.
Student.changeSchool();
}
In the above code, despite not instantiating a object of type Student, we can still call the changeSchool method in the main class. However, note that the variable school will be changed for ALL Student objects! Yes ALL. Even Students who were created before the changeSChool method was called.
Observe:
class Student{
int age;
String name;
Static String school = "CPP";
static void changeSchool(){
school = "Harvard';
}
void printSchool(){
System.out.println(school);
}
}
class Main(){
.
.
.
Student a = new Student();
Student b = new Student();
a.changeSchool();
a.printSchool();
b.printSchool();
}
Harvard
Harvard
In the above example, the school variable for B was changed despite not calling b.changeSchool(). Because the school variable is static, all student objects share the same memory space for the school variable. Changing the variable for one object will still affect other Student objects.
Scope is used to define the spatial location of where a variable is visible. A simpler definition is, the space between where a variable can be used.
Look at the following example:
1 for (int i = 0; i < 10; i++){
2 System.out.println(i);
3 }
4 System.out.println(i);
ERROR
Because the scope of int i is between lines 1 and 3, using the variable outside of it's scope will result in a error as the program does not know where the variable is. However it also means that the variable is basically free to be reassigned.
For example:
1 for (int i = 0; i < 10; i++){
2 System.out.println(i);
3 }
4 double i = 10;
5 System.out.println(i);
10
In the above example the variable i was 'recreated' as a double as the variable was no longer 'alive' outside of its scope.
The same applies for methods and classes as well. Variables declared within a method or object cannot be viewed outside of its scope unless the variable is passed back.
Note that global variables (variables that are declared inside a class but not within a method), can be seen by any other method as the scope of that variable is the entire class.
class Scope{
int global = 10; //This variable can be seen anywhere within the Scope class
public static void main (String[] args){
int x = 5; //X can only be seen within scope2 normally
int y = 1; //
scope2(y);
static void scope2(int y){
/*Variable y is 'visible' because it was passed as a variable, however it's simply another variable with the same
name that contains the same value as y. Variable X and it's data cannot be seen at all as it was not passed. However
the global variable is still visible.*/
}
}