OBJECTS - JAVA: Learn JAVA Quickly (2017)

JAVA: Learn JAVA Quickly (2017)

CHAPTER 5. OBJECTS

OOP

Object-oriented programming is a way of thinking for solving programming problems. Everything about this is connected with concept of object. Our mission is to somehow recognize relationships between objects(entities) from real world and “transfer” them to our code.

In Java, all starts with classes. Variable, methods and objects are placed inside classes. Objects are created by instantiating classes. Every entity has attributes and methods.

How we can group our data? Using arrays.

String[][] person = new String[1][3];

person[0][0] ="Name";

person[0][1] ="Surname";

person[0][3] ="Birthdate";

Using classes? Much more natural.

Let`s do some programming. In our current project make new package called second.pack. Inside that package add class called Car, but without main method. Our Car class will contain one attribute activate, and two methods start and stop.

booleanactivate;

void start() {

activate = true;

}

void stop() {

activate = false;

}

We said that default value for boolean primitive type is false. Usage of start() and stop() methods is to change value of activatevariable.

Now we need another class for making this more interactive. In new class Test will be created Car object and called method.

Note: Just like it is mentioned, methods are supposed to be called inside main method. So, we need to place this code inside that method. Main method does not need to be implemented by default, it could be written just like any other method. Also, void keyword will be explained a little later.

Car bmw = newCar();//Car object created by keyword new

bmw.start();//reference of Car object used to call start() method

By calling start() method on our Car object value of activate attribute is set to true. But calling stop() method on same object value will be false. This program won`t print anything to console, don`t get confused.

Try it out. Make your own simple project. Imagine that you are in classroom for example. Make object of yourself, add attributes and methods. Methods could be based on condition if you are passed exam or not.


It is possible to initiate reference which doesn`t point to any object. Reference still exists on stack, but there is no new object created on heap.nullis not object, You cannot instantiate or create variables of this type though. Method invocation on a nullresults in a NullPointerException.

Car opel = null;

What if we have this situation:

Car a = newCar();

Car b = newCar();

Note: Objects are supposed to be created by using keyword new.

b = a;

Operator= is only coping a reference, not object.

CONSTRUCTORS

Constructor is used to initialize object. Constructor is automatically called by creation of object and must have same name as class. There is a two type of constructors:

· Default constructor (no-arg constructor)

For our coding we need new class Studentwith main method. Inside that method create new Student object like this:

Student stud = newStudent();

Constructors are special methods, so we are creating them outside main method:

Student() {

}

Note: If default constructor is not created, compiler will do that by default. To be sure that constructor is called let`s leave some massage inside him and run program:

Student() {

System.out.println("Student is created!");

}

expected: Student is created! will be printed to console

· Parameterized constructor

For this purpose, we need class Professor (without main method) and class Faculty (with main method). Class Professor will contain attributes and method along with parameterized constructor:

String name;

intage;

String city;

Professor(String n, inta, String c) {

this.name = n;

this.age = a;

this.city = c;

}

void print() {

System.out.println(name + " " + age + " " + city);

}

Note: this keyword means that we are referring to current object. Current object is object in class which we are using.

Now we want to make this functional. Do you remember when method and constructor are called? By creation of object, for sure. So, let`s do that in

Faculty class and run program:

Professor prof = newProfessor("Ivan", 35, "Moscow");

prof.print();

expected: Ivan 35 Moscow will be printed to console

On this example is clearly shown usage of parameterized constructor. Try to delete parameters from Professor object. It will make some error: The constructor Professor() is undefined

METHODS

modifierreturn_type name (parameters) {

body

}

return

We already covered methods and learned how to write most of them. But, not all methods are the same. For this we need Area class with main method. First method with return keyword will be explained:

publicstaticint countArea(intwidth, intheight) {

returnwidth * height;

}

public static – modifier, what will be explained a bit latter

int – return type

This method need to be called somehow. In this case, we are aiming to print out result of width * height. To do that, println will help us, so this code will be put inside main method:

System.out.println(countArea(3, 5));

expected: 15 will be printed to console

VOID

As we saw, methods that have return keyword return some value. That value could be later on used for some operation. But what if we don`t want to return anything. Just to print any massage or something like that. How to make that method? We need class VoidMethods with main method implemented. Our method will check input and based on that condition will print relevant result. Try to make it on your own, it you got stuck see this code:

staticvoid seasonOfYear(String s) {

if(s == "Spring") {

System.out.println("It is spring!");

} elseif (s == "Summer") {

System.out.println("It is summer!");

} elseif (s == "Autumn") {

System.out.println("It is autumn!");

} elseif (s == "Winter") {

System.out.println("It is winter!");

} else {

System.out.println("You made mistake, sorry");

}

}

It is not hard to figure out that we have String parameter which is used based on input when method is called. So to do that, inside our main method we need to call seasonOfYear(String s) method:

seasonOfYear("Summer");

expected: Summer will be printed to console