Java Object-Oriented Programming I

Introduction

Java Object-Oriented Programming I

Contents

  1. Class in Java
  2. Constructor in Java
  3. this and super keyword in Java
  4. this() vs super() call
  5. Static vs Instance variables in java
  6. Static vs Instance methods in Java

Class in Java

A class which is a fundamental component of Object-Oriented Programming in Java.

A class is a blueprint that defines the variables and the methods common to all objects of a certain kind. Simply, a blueprint for creating objects.

  • Only one public class is allowed in one source file

What is an objects is in Object-Oriented Programming?

Objects have two major characteristics, the state, and behavior. A programming language object stores its state in fields(variables) and executes their behavior with methods.

In Java, When we create a new project, it creates a new class for us, and it calls the class Main public class Main{}, inside the Main class, it also creates the method main public static void main(String[] args){}.

sample/Main.java

package sample;

public class Main {
    public static void main(String[] args) {
    }
}

Let’s Create People Class

sample/People.java

package sample;

public class People {
    
}

Access modifier: public, private, protected.

  • public keyword is an access modifier that we determine what access we want to allow others to have to the class that is created.
    • the world public means unrestricted access to the class.
  • private keyword that is no other class can access that class.
  • protected keyword that allows classes in the same package to access the class.

You have seen variables used inside a method. That is Local variables. In Java you can not access those local variables outside of the method. Also, if your variables inside a block, you can not access outside of the block.

However, classes allow us to create variables that can be seen and are accessible from anywhere within the class that is created. these are known as member variables or fields. when you create a field (member variables) in class, you need to also specify an excess modifier that works the same way as the excess modifier for a class definition.

A general rule, when you define a field(member variables) in class, with the access modifier private, unlike the class where we have gone with public.

So what private means in fields (member variables). That is encapsulation. In java, encapsulation is used to hide the fields and methods.

Let’s Fields in People Class and We build an object that is base on the People.

sample/People.java

package sample;

public class People {
    private String name;
    private String country;
    private String language;
}
  • create fields(members variables) in People Class.

sample/Main.java

package sample;

public class Main {
    public static void main(String[] args) {
        People tim = new People();
        People Mike = new People();
    }
}

objects (tim, and mike) that is base on the People class. But objects can not access the fields of People class because all the fields are private in the People class. So, we need to create a public method with a parameter to update fields.

sample/People.java

package sample;

public class People {
    private String name;
    private String country;
    private String language;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }
}

Add setName and getName Method to update and get a name field at another class.

sample/Main.java

package sample;

public class Main {
    public static void main(String[] args) {

        People tim = new People();
        People mike = new People();
        tim.setName("Tim");
        System.out.println("Name: " + tim.getName());

    }
}

Now, you can set up object(tim)’s name.

Let’s execute with command line

$ javac sample/*.java
$ java sample.Main
Name: Tim
  • at a project root directory
    • 1. compile all java files that are Main.java and People.java.
    • 2. Execute Main in the named sample package.

Thus, with private fields(member variables) and public methods to update and use fields. That is the whole concept of encapsulation is that we are not allowing people to access the field directly, and we can add some validation when we assign data to fields.

// you can add some validations.
   public void setName(String name) {
        if (name.toLowerCase().equals("tim")) {
            this.name = name;
        } else {
            this.name = "?";
        }
    }

2. Constructor in Java

A constructor in Java is a special method that is used to initialize objects.

  • a constructor method name should be the same as the class name
  • a constructor method can be method overloading.
  • an object is created using the new() keyword, a constructor is called.
  • It calls a default constructor if there is no constructor available in the class

sample/People.java

package sample;

public class People {
    private String name;
    private String country;
    private String language;

    public People(){
        System.out.println("Empty Constructor is called");
    }

    public People(String name, String country, String language){
        System.out.println("A Constructor with three parameters is called");
        this.name = name;
        this.country = country;
        this.language = language;
    }

    public String getName(){
        return this.name;

    }
}

There are two constructors which are people an empty parameter constructor, and a constructor with three parameters. getName method will use to get the object’s name that will be set up by calling a constructor with three parameters.

sample/Main.java

package sample;

public class Main {
    public static void main(String[] args) {

        People tim = new People();
        
        // Using the constructor method, initialize an object.
        People mike = new People("Mike", "Spain", "Spanish");
        System.out.println(mike.getName());
    }
}
Empty Constructor is called
A Constructor with three parameters is called
Mike
  • When a tim object is created, an empty constructor is called.
  • When a mike object is created, a constructor with three parameters is called.

You can see with the method is called with printed messages. Also, with a constructor, you do not have to set a value individually. You will see a constructor extensively in Java because constructors are a very important part of creating objects from classes.

3. this and super keyword in Java

The keyword super is used to access and call the parent class members (variables and methods).

This keyword this is used to call the current class members (variables and methods). This is required when we have a parameter with the same name as an instance variable (field).

We can use super and this keyword anywhere in a class except a static block and a static method

In the getter we don’t have any parameters so the this keyword is optional

Keyword this

The keyword this is commonly used with constructors and setters.

class People {
    private String name;
    private int age;

    // Create Constructor
    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String move() {
        return this.name + " is moving";
    }

    /**
     * @return String return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return int return the age
     */
    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {

        People myBestFriend = new People("Tim", 35);

        // my best friend Tim changes his name.
        myBestFriend.setName("Jake");

        System.out.println(myBestFriend.getName());
    }
}
Jake

There are this in the People constructor and setName method.

Keyword super

The keyword super is commonly used with method overriding

class ParentClass {
    public void printValue() {
        System.out.println("This is the method in ParentClass");
    }
}

class ChildClass extends ParentClass {
    @Override
    public void printValue() {
        super.printValue();
        System.out.println("The printValue method is called in ChildClass");
    }
}

public class Main {
    public static void main(String[] args) {

        ChildClass childClass = new ChildClass();
        childClass.printValue();

    }
}
This is the method in ParentClass
The printValue method is called in ChildClass

Without the super keyword in the method overriding, in the case it would be recursive call. the method would call it self forever.

4. this() vs super() call

this() to call a constructor from another overloaded constructor in the same class. To call to this() can be used only in a constructor, and must be the first statement in a constructor changing, in other words when one constructor calls another constructor, and it will reduce duplicated code.

The only way to call a parent constructor is by calling super(). This calls the parent constructor.

The Java Compiler puts a default call to super() if we do not add it, and it is always the no-args super which is inserted by the compiler (constructor without arguments). The call to super() must be the first statement in each constructor. Even Abstract classes have constructors, although you can never instantiate an abstract class using the new keyword. An abstract class is still a super class, so its constructors run when someone makes an instance of a concrete subclass.

A constructor can have a call to super() or this() but never both.

Bad Constructors.

class People {
    private String name;
    private int age;

    public People() {
        this.name = "undefined";
        this.age = 0;
    }

    public People(String name) {
        this.name = name;
        this.age = 0;
    }

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
  • There is repeated code in every constructor. we are initializing variables in each constructor with some default values.

You should never write constructors like this.

Better Constructors with this()

class People {
    private String name;
    private int age;

    // first constructor
    public People() {
        // calls second constructor
        this("undefined");
    }

    // second constructor
    public People(String name) {
        // calls third constructor
        this("undefined", 0);
    }

    // third constructor
    public People(String name, int age) {
        // initialize variables
        this.name = name;
        this.age = age;
    }
}

The first constructor calls the second constructor and the second constructor calls the third constructor with this()

This is know as constructor chaining, the last constructor has the “responsibility” to initialize the variables.

Super() call

class ParentClass {
    private String parentName;
    private String parentCountry;

    public ParentClass(String parentName, String parentCountry) {
        this.parentName = parentName;
        this.parentCountry = parentCountry;
    }
}

class Me extends ParentClass {

    private String name;
    private String country;

    // first constructor
    public Me(String name, String country) {
        // calls second constructor
        this("Undefined", "Undefined", name, country);
    }

    // second constructor
    public Me(String parentName, String parentCountry, String name, String country) {
        // calls constructor from parent
        super(parentName, parentCountry);
        this.name = name;
        this.country = country;
    }
}

With super(), you can use the constructor of the parent class or super class.

5. Static vs Instance variables in java

Static Variables

  • Declared by using the keyword static.
  • Static variables are also known as static member variables.
  • Every instance of that class shares the same static variable.
  • If changes are made to that variable, all other instances will see the effect of the change.
  • Static variables are not used very often but can sometimes be very useful.
    • when reading user input using the Scanner class we will declare a scanner as a static variable.
  • That way static methods can access it directly.

Static variable

package anote;

class Car {

    private static String name;

    public Car(String name) {
        Car.name = name;
    }

    public void carName() {
        System.out.println("Car name: " + name);
    }

}

public class Main {
    public static void main(String[] args) {

        Car ferrari_F40 = new Car("Ferrari_F40");
        Car aventador = new Car("Aventador");

        ferrari_F40.carName();
        aventador.carName();
    }
}
Car name: Aventador
Car name: Aventador

Why can name are the same Aventador?

The static variables share the variable between instances.

This particular example, it is better to use instance variable.

Instance Variables

  • They do not use the static keyword.
  • Instance variables are also known as fields or member variables.
  • Instance variables belong to an instance of a class.
  • Every instance has it is own copy of an instance variable.
  • Every instance can have a different value (state).
  • Instance variables represent the state of an instance.

Instance Variables

package anote;

class Car {

    private String name;

    public Car(String name) {
        this.name = name;
    }

    public void carName() {
        System.out.println("Car name: " + name);
    }

}

public class Main {
    public static void main(String[] args) {

        Car ferrari_F40 = new Car("Ferrari_F40");
        Car aventador = new Car("Aventador");

        ferrari_F40.carName();
        aventador.carName();
    }
}
Car name: Ferrari_F40
Car name: Aventador

6. Static vs Instance methods in Java

Static Methods

  • Static methods are declared using a static modifier.
  • Static methods can not access instance methods and instance variables directly.
  • Static methods usually used for operations that do not require any data from an instance of the class (from this).
  • This keyword is the current instance of a class.
  • A method that does not use instance variables that method should be declared as a static method.

main is a static method and it is called by the JVM when it starts an application.

Static Method

package anote;

public class Main {
    public static void main(String[] args) {

        int result = Calculator.sum(3, 2);
        System.out.println(result);

        hello("world");
    }

    public static void hello(String word) {

        System.out.println("hello " + word);
    }
}

class Calculator {
    public static int sum(int a, int b) {
        return a + b;
    }
}

Static method do not require to create instance. Just called class name dot method name to access them.

Instance Methods

  • Instance methods belong to an instance of a class.
  • To use an instance method we have to instantiate the class first usually by using the new keyword.
  • Instance methods can access instance methods and instance variables directly.
  • Instance methods can access static methods and static variables directly.
package anote;

public class Main {
    public static void main(String[] args) {

        Car car = new Car();
        car.engineSound();
    }
}

class Car {
    //instance methods do not use static keywords
    public void engineSound() {
        System.out.println("www");
    }
}

Static or instance method?

Does it use any fields (instance variables) or instance methods?

  • if yes, instance method
  • if no, static method

Leave a Reply

Your email address will not be published.

ANOTE.DEV