3.1 Defining Class, Adding Method to Class, Creating Object and Calling Method

A class acts as a template or blueprint for objects, establishing new data types that can be instantiated [cite: 1434]. You outline the data it encompasses and the code that manipulates that data [cite: 1445].

Objects: An object is created based on a blueprint called a class, which defines what the object can do and what information it holds [cite: 1464]. It encapsulates data (member variables) and behavior (methods) [cite: 1486].

Methods: Member functions, or methods, encapsulate the behavior or actions that objects can perform [cite: 1504]. Methods promote code reusability, modularity, and maintainability [cite: 1506].


class Dog {

    // Member variables

    String breed;

    int age;


    // Adding a method to the class

    void bark() {

        System.out.println("Woof!");

    }

}


public class Main {

    public static void main(String[] args) {

        // Creating an object

        Dog myDog = new Dog();

       

        // Calling the method

        myDog.bark();

    }

}



3.2 Abstraction and Encapsulation

Encapsulation: Encapsulation is the mechanism of wrapping data (variables) and code acting on the data (methods) together as a single unit. In Java, access modifiers control the visibility and accessibility of class members [cite: 1516]. Making variables private restricts access to the member within the same class [cite: 1519], preventing direct unauthorized modification [cite: 1532]. Controlled access is then provided using public accessor (getters) and mutator (setters) methods [cite: 1533].

Abstraction: Abstraction hides complex internal implementation details and shows only the essential features of the object to the user. While encapsulation focuses on hiding data, abstraction focuses on hiding implementation complexity.

3.3 Constructors and its Type (Default, Parameterized and Copy)

A constructor is a special type of method with the same name as the class that is used to initialize new objects [cite: 1580]. By assigning initial values to an object's attributes, constructors ensure that an object starts its life in a consistent state [cite: 1581].

  • Default Constructor: A constructor that doesn't take any parameters [cite: 1600]. It initializes the object with default values [cite: 1602]. Java automatically provides one if no other constructors are explicitly defined.
  • Parameterized Constructor: Takes parameters to initialize the object with specific values [cite: 1610]. It allows for customization of object initialization by accepting arguments during object creation [cite: 1611].
  • Copy Constructor: A constructor that initializes a newly created object using the values of an existing object of the same class.

class Student {

    String name;

   

    // 1. Default Constructor

    public Student() {

        name = "Unknown";

    }

   

    // 2. Parameterized Constructor

    public Student(String name) {

        this.name = name;

    }

   

    // 3. Copy Constructor

    public Student(Student s) {

        this.name = s.name;

    }

}



3.4 'this' Keyword

The this keyword is used within a constructor or method to distinguish between the class-level member variables and the parameters, as both can have the same names [cite: 1480]. It explicitly refers to the current object's variables, ensuring that the values provided in the parameters are correctly assigned to the object's fields [cite: 1481].

3.5 Static Fields and Methods

A static variable (field) is a type of variable that is shared among all instances of a class [cite: 198]. Because it is attached to the class rather than any individual object, memory is allocated only once.

Static methods belong to the class rather than instances. They can be invoked without creating an object of the class. A static method can only directly access other static fields and methods; it cannot access instance variables or instance methods.

3.6 More on Method: Passing by Value, Passing by Reference

Java operates strictly on the principle of passing arguments by value [cite: 1648].

  • Passing Primitive Types: A copy of the actual value is passed. Modifying it inside the method does not affect the original variable.
  • Passing Objects: When you pass an object to a method, you pass the object's reference, not the object itself [cite: 1648]. What is being passed is a copy of the object's reference [cite: 1649].

Since the method references the same object, changes in the method affect the original object [cite: 1651]. However, if you attempt to reassign the object to a new object within the method, the original reference outside the method remains unchanged [cite: 1652].

3.7 Recursion

Recursion is a programming technique where a method calls itself continuously to solve a smaller piece of a larger problem. A recursive method must have two parts:

  1. Base Case: The condition under which the recursion stops.
  2. Recursive Case: The part where the method calls itself with modified parameters to progress toward the base case.

public int factorial(int n) {

    if (n == 0) { // Base case

        return 1;

    } else { // Recursive case

        return n * factorial(n - 1);

    }

}



3.8 Nested and Inner Class

Java allows a class to be defined within another class. These are called nested classes and they are useful for logically grouping classes that are only used in one place.

Nested and Inner Class . Modifications.


3.9 Variable Length Arguments (Varargs)

Variable length arguments (varargs) allow a method to accept zero or multiple arguments of a specified type. It simplifies the creation of methods that need to take a variable number of arguments. It is indicated by three dots (...) following the data type.

  • There can be only one varargs parameter per method.
  • The varargs parameter must be the last parameter in the method signature.

public void printNumbers(int... numbers) {

    for (int num : numbers) {

        System.out.println(num);

    }

}

// Can be called as printNumbers(1, 2, 3) or printNumbers(5)



3.10 Package: Defining and Importing Package

A package in Java is used to group related classes, interfaces, and sub-packages. Packages help in avoiding name conflicts and can be used to control access visibility.

  • Defining a Package: Use the package keyword at the very top of the Java source file. Example: package com.university.courses;
  • Importing a Package: To use a class from another package, it must be imported using the import keyword. For example, to handle inputs, the java.util.Scanner package is imported to access the Scanner class [cite: 723]. For file operations, the java.io package allows a programmer to create File objects [cite: 1724].