Object-Oriented Programming (OOP) – JAVA

Credit to this website:

https://www.w3schools.com/java/java_oop.asp

Java – What is OOP?

OOP stands for Object-Oriented Programming.

Pseud code programming is about writing procedures or methods/functions that perform operations on the data,

However, object-oriented programming is about creating objects that contain both data and methods/functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time.

 

Java Class & Attributes

public class MyClass {  // This is class named "MyClass"
    int x = 5;  // variables
    String firstName = "Qaisara"; // Variables
    String lastName = "Shaharil"; // Variables


    //In Java, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.
    //To create an object of MyClass, specify the class name, followed by the object name, and use the keyword new:

    public static void main(String[] args){
        MyClass myObj1 =  new MyClass();
        System.out.println(myObj1.x); //access attributes/variable x by creating an object of the class
        MyClass myObj2 = new MyClass();
        System.out.println(myObj2.x);

        MyClass myObj3 = new MyClass();
        myObj3.x = 20; // Modify the attributes x
        System.out.println(myObj3.x); // The myObj3 is set to 20.
        System.out.println(myObj2.x); // The myObj2 is maintain = 5 although myObj3 has modify the x

        MyClass myObj4 = new MyClass();
        System.out.println("Name: " + myObj4.firstName + " " + myObj4.lastName);
    }
}

 

Java Class & Methods

We created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:

public class MyClass {
    //Static method/function
    static void myStaticMethod(){
        System.out.println("Static methods can be called without creating objects");
    }
    //Public method
    public void myPublicMethod(){
        System.out.println("Public methods must be called by creating objects");
    }

    //Main method
    public static void main(String[] args){
        myStaticMethod(); //Call the static method
        //myPublicMethod();

        MyClass myObj = new MyClass();
        myObj.myPublicMethod(); //call the public method. Need to create the object first

    }

}

Others example of public methods:

public class Car {

    public void fullThrottle(){  //public method/function. Need to create object first.
        System.out.println("The car is going as fast as it can!!!");
    }

    public void speed(int maxSpeed){
        System.out.println("Max speed is: " + maxSpeed);
    }

    public static void main(String[] args){
        Car myCar = new Car();      // Create an object named myCar
        myCar.fullThrottle();       // Call the fullThrottle() method
        myCar.speed(200); //Call the speed() method

    }
}


Access public method from other class:
public class OtherClass {

    public static void main(String[] args){
        Car2 myCar = new Car2();
        myCar.fullThrottle();
        myCar.speed(300);
    }
}

public class Car2 {
    public void fullThrottle(){  //public method/function. Need to create object first.
        System.out.println("The car is going as fast as it can!!!");
    }

    public void speed(int maxSpeed){
        System.out.println("Max speed is: " + maxSpeed);
    }

}

Java Constructors

A special method/functions that is used to initialize objects.  The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Constructor with parameters

//Creat a class named MyClass
public class MyClass {

    int x; // create a class attribute named x as integer


    public MyClass(){ // create a class constructor for MyClass class. This will initial value of x.
        x = 5;
    } // constructor

    public static void main(String[] args){ // main method
        MyClass myObj = new MyClass();
        System.out.println(myObj.x);
    }
}
Constructor with parameters
public class Car {
   int modelYear;
   String modelName;
   public Car(int year, String name){ // Constructor
       modelYear = year;
       modelName = name;
   }

    public static void main(String[] args){
        Car myObj = new Car(1985,"Proton");
        System.out.println(myObj.modelYear + " " + myObj.modelName);

    }
}

Java Modifiers

Access Modifiers

For classes, you can use either public or default:

Modifier Description
public The class is accessible by any other class
default The class is only accessible by classes in the same package. This is used when you don’t specify a modifier. You will learn more about packages in the Packages chapter

For attributes, methods and constructors, you can use the one of the following:

1) public – The code is accessible for all classes
// Class named Person
public class Person {
    public String fname = "Qaisara";
    public String lname = "Shaharil";

}

//Class named MyClass
public class MyClass {
    public static void main(String[] args){

        Person myObj = new Person();
        System.out.println("First Name : " + myObj.fname);
        System.out.println("Last Name : " + myObj.lname);
    }
}
2) protect  – The code is only accessible within the declared class. Can be said local variables.
//Class named Car has private variables/attributes 
public class Car {
    private String fcar = "Proton";  
    private String scar = "Honda";
}
//
public class MyClass {
public static void main(String[] args){

Person myObj = new Person();
System.out.println("First Name : " + myObj.fname);
System.out.println("Last Name : " + myObj.lname);

Car myObj2 = new Car();
System.out.println(myObj2.fcar); // Will be an error because fcar is private access in Car
}
}

Java Packages

The Java API is a library of prewritten classes, that are free to use. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. To use a class or a package from the library, you need to use the import keyword:

import package.name.Class;   // Import a single class
import package.name.*;   // Import the whole package For example:Using the Scanner class to get user input:
import java.util.Scanner;

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}

Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group the “inheritance concept” into two categories:

  • subclass (child) – the class that inherits from another class
  • superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass – child) inherits the attributes and methods from the Vehicle class (superclass-parent):

// A superclass (parent) name Vehicles
class Vehicles {
    protected String brand = "Ford"; // Only can be accessed by subclass (child)
    public void honk(){     // A method/function name honk
        System.out.println("Beep Beep");
    }
}
// A subclass(child) name Car. Where the parent is Vehicles
class Car extends Vehicles{

        public static void main(String[] args){
            //Write the class name, followed by the object name, and use the keyword new:
            Car myObj = new Car(); // Create an object named myObj
            System.out.println(myObj.brand);

            Car myObj2 = new Car(); // Create an object named myObj2
            myObj.honk(); // Call honk()
        }
}

Think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds – And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

class Animal { // Superclass - parent
    public void animalSound(){
        System.out.println("Animal makes a sound");
    }
}
class Pig extends Animal{ // Subclass - child
    public void animalSound(){
        System.out.println("The pig says: Wee Wee");
    }
}
class Dog extends Animal{ // Subclass - child
    public void animaSound(){
        System.out.println("The dog says: Bow Bow");
    }
}
class MyMainClass{
    public static void main(String[] args){
        Animal myAnimal = new Animal(); //Create an object
        myAnimal.animalSound();
        Animal myPig = new Pig();
        myPig.animalSound();
    }
}

Java Inner Classes/ Nest Classes

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable. To access the inner class, create an object of the outer class, and then create an object of the inner class:


class OuterClass {
    int x = 10;
    class InnerClass{
        int y = 5;
    }
}
public class MyClass {
    public static void main(String[] args){
        OuterClass myOuter = new OuterClass(); // create obj to outer class
        System.out.println(myOuter.x);  // print out the outer class
        OuterClass.InnerClass myInner = myOuter. new InnerClass(); // create obj to inner class
        System.out.println(myInner.y);  // print out the inner class
    }
}

Java User Input (Scanner)

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

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

import java.time.LocalDate;
import java.util.Scanner; // Import the Scanner class
public class MyClass {
    public static void main(String[] args){
        Scanner myObj = new Scanner(System.in); // Create a Scanner object
        System.out.println("Enter your name: ");

        String name = myObj.nextLine(); // Reads a String value from the user
        System.out.println("Your name is " + name);

        System.out.println("Enter you age: ");
        int age = myObj.nextInt(); // Reads a int value from the user
        System.out.println("Your age is " + age);
        
        LocalDate myObj2 = LocalDate.now(); // Create a localDate object
        System.out.println(myObj2);  // Print out the date
    }
}

Java Exceptions – Try…Catch

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs.

try {
  //  Block of code to try
}
catch(Exception e) {
  //  Block of code to handle errors
}
Examples:
public class MyClass {
    public static void main(String[] args){
        try{
            int[] myNumbers = {1,2,3}; //the array only have index 0,1,2
            System.out.println(myNumbers[10]);
        }catch (Exception e){
            System.out.println("Something went wrong !!!");
        }
    }
}

Java Keywords

You all can refer to this website for your reference on keywords.