Java Definitions III

Introduction

Java Definitions III

Contents

  1. Class, Instance, Object, an Reference in Java
  2. Method Overloading in Java
  3. Control Flow Statements in Java
  4. User Input with Scanner in Java
  5. Method Overloading and Overriding

1. Class, Instance, Object, an Reference 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.

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.

As you know, a class provides the blueprint for objects. you create an object from a class, and the object is an instance of a class

People tim = new People();

tim is an instance

Lastly, A reference is an address that indicates where an object’s variables and methods are stored.

Class People

package sample;

public class People {
    private String name;
    private int age;

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

    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;
    }
}

Instances of the People Class in Main Class

package sample;

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

        People tim = new People("Tim", 45);
        People mike =new People("mike", 30);

        System.out.println(tim.getName());
        System.out.println(tim.getAge());

        System.out.println(mike.getName());
        System.out.println(mike.getAge());
        
    }
}

A class People with instance variables (fields) name and age. In the Main Class, we create tim and mike objects which are instances of the people class.

the tim and mike objects are a reference to the object in memory.

an Instance of People Class
People tim = new People("Tim", 45);
People myfriend = tim

If we assign a myfriend and defined as tim, the reference of myfriend and tim is the same. we have two references pointing to the same object in memory.

The same reference

*An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks.

In java you have references to an object in memory, there is no way to access an object directly. Everything is done with a reference.

2. Method Overloading in Java

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different Parameters (implementations).

Method overloading is a feature that allows us to have more than one method with the same name with different parameters.

public class MethodOverloading {
    public static void main(String[] args) {
        System.out.println(multiplyByTwo("jay", 500));
        System.out.println(multiplyByTwo(500));
    }

    public static int multiplyByTwo(String name, int score) {
        System.out.println("Edited by " + name);
        return score * 2;
    }

    public static int multiplyByTwo(int score) {
        return score * 2;
    }
}
Edited by jay
1000
1000
  • MultiplyByTwo Method is an Overloading Method.
    • multiplyByTwo(String name, int score)
    • multiplyByTwo(int score)

The built-in method PrintIn is also Overloading Method in Java.

public class MethodOverloading {
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println(1.1);
        System.out.println("string");
    }
}
  • A printIn method with different parameters (integer, double, string, and more)

Benefit of Method Overloading

It improves code readability and re-usability.

3. Control Flow Statements in Java

In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.

  1. if then else Statement
  2. Switch Statement
  3. for Statement
  4. while Statement
  5. do-while Statement

If then else statement

If then else statement to specify a block of Java code to be executed if a condition is true .

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

        // If then else Statement
        boolean value = false;
        if (value) {
            System.out.println("Value is " + value);
        } else if (!value) {
            System.out.println("Value is " + value);
        }
        else {
            System.out.println("Value is not boolean");
        }
    }
}
Value is false

Switch Statement

Switch statement to select one of many code blocks to be executed.

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

        // Switch Statement
        int value = 1;
        switch(value){
            case 1:
                System.out.println("Value is 1");
                break;
            case 2:
                System.out.println("Value is 2");
                break;
            case 3:case 4: case 5:
                System.out.println("Value is 3 or 4, or 5");
                break;
            default:
                System.out.println("Value is not 1,2,3,4,5");
                break;
        }

    }
}
Value is 1
  • Breaks are vital to close the case comparison
  • Switch value is able to use the primitive types byte, short,char, and int
  • After JDK version 7 String can use as Switch value.

for Statement

for statement is used to loop some code so in other words it is going to allow us to execute code a certain number of times.

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

        // for loop print 0 to 4
        for (int i = 0; i < 5; i++){
            System.out.println(i);
        }
    }
}
0
1
2
3
4

while Statement

While statement (loop) will execute the code block until the condition is false.

The while loop check the condition at the start before executing the the code block

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

        // while loop print 0 to 4
        int i = 0;
        while (i < 5){
            System.out.println(i);
            i++;
        }
    }
}
0
1
2
3
4

Use break;

The break keyword can be used in any of the loop control structures. It causes the loop to immediately stop while loop.

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

        // while loop print 0 to 4
        int i = 0;
        while (true){
            if (i == 5){
                break;
            }
            System.out.println(i);
            i++;
        }
    }
}
0
1
2
3
4

Use continue;

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

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

        // while loop print 0,1,2,4 without 3
        int i = 0;
        while (i < 5) {
            if (i == 3) {
                i++;
                continue;
            }
            System.out.println(i);
            i++;
        }
    }
}
0
1
2
4

If you want to use true as while loop condition, be careful to Infinite loop.

do-while Statement

do while loop will always execute the code block at least once and also execute the code block until the condition is false.

do while loop the code block is executed at least once then the condition is checked.

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

        // do-while loop print 0 to 4
        int i = 0;
        do {
            System.out.println(i);
            i++;
        }while(i < 5);
    }
}
0
1
2
3
4
  • do-while loop while( i < 5); semicolon is needed.

4. User Input with Scanner in Java

The Scanner class is used to get user input, and it is found in the java.util package.

import java.util.Scanner;

public class UserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your country: ");
        String country = scanner.nextLine();
        System.out.println("your country is "+ country);
        scanner.close();
    }
}
Enter your country: 
seoul
your country is seoul

nextLine() method, which is used to read Strings.

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number x * 5 = ? ");
        boolean hasNextDouble = scanner.hasNextDouble();

        if (hasNextDouble){
            Double number = scanner.nextDouble();
            System.out.println(number * 5);
        }
        else{
            System.out.println("Please enter number");
        }
        scanner.close();
    }
}
Enter number x * 5 = ? 
4
20.0
  • with hasNextDouble() check user input is number(double type) or not.

nextDouble() method, which is used to read Double Data type.

Input types

nextBoolean()Reads a boolean value from the user
nextByte()Reads a byte value from the user
nextDouble()Reads a double value from the user
nextFloat()Reads a float value from the user
nextInt()Reads a int value from the user
nextLine()Reads a String value from the user
nextLong()Reads a long value from the user
nextShort()Reads a short value from the user

5. Method Overloading and Overriding

Method Overloading

  • Method overloading means providing two or more separate methods in a class with the same name but different parameters.
  • Method return type may or may not be different and that allows us to reuse the same method name.
  • Method overloading is very handy, it reduces duplicated code and we do not have to remember multiple method names.
  • Method overloading does not have anything to do with polymorphism but java developers often refer to overloading as Compile Time Polymorphism.
  • In other words, the compiler decided which method is going to be called based on the method name, return type, and argument list.

Method overloading happens inside a single class, but a method can also be treated as overloaded in the subclass of that class that is because a subclass inherits one version of the method from the parent class and then the subclass can have another overloaded version of the method.

Rules

  • Methods must have the same method name.
  • Methods must have different parameters.
  • Methods may or may not have different return types.
  • Methods may or may not have different access modifiers.
  • Throw different checked or unchecked exceptions.

Method overriding

  • Method overriding means defining a method in a child class that already exists in the parent class with same signature (same name, same arguments)
  • By extending the parent class the child class gets all the methods defined in the parent class (those methods are also known as derived methods).
  • Method overriding is also known as Runtime Polymorphism and Dynamic Method Dispatch because the method that is going to be called is decided at runtime by the JVM.
  • When we Method override a method it’s recommended to put @Override immediately above the method definition. This is an annotation that the compiler reads and will then show us an error if we do not follow overriding rules correctly.
  • We can not override static methods only instance methods.

Rules

  • It must have the same name and same arguments
  • Return type can be a subclass of the return type in the parent class.
  • It can not have a lower access modifier.
  • For example, if the parent method is protected then using private in the child is not allowed but using public in the child would be allowed.
  • Only inherited methods can be overridden, in other words, methods can be overridden only in child classes.
  • Constructors and private methods cannot be overridden.
  • Methods that are final cannot be overridden
  • A subclass can use super.methodName() to call the superclass version of an overridden method.

Method overloading

package anote;

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

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

    }
}

// Method overloading in the same class
class Car {
    public void engineSound() {
        System.out.println("www");
    }

    public void engineSound(int num) {

        String sound = "";
        for (int i = 0; i < num; i++) {
            sound = sound + "w";
        }
        System.out.println("www" + sound);
    }
}
java anote/Main.java
www
wwwwwwww

Method overriding

package anote;

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

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

// Override with a inherited method
class Car {
    public void engineSound() {
        System.out.println("www");
    }
}

class Lamborghini extends Car {

    @Override
    public void engineSound() {
        System.out.println("boooooaaaa!!!");
    }
}
java anote/Main.java
www
boooooaaaa!!!

Leave a Reply

Your email address will not be published.

ANOTE.DEV