Java for Beginners

September 16th, 2023


Week 2: Classes and Objects

Class 3: Introduction to Classes and Objects

Understanding Classes and Objects

In Week 1, we introduced you to the basics of Java programming. Now, in Week 2, we’ll dive deeper into the core of Java - classes and objects. Understanding classes and objects is fundamental to object-oriented programming (OOP).

What is a Class?

  • A class is like a blueprint or template for creating objects.
  • It defines the structure and behavior of objects that will be created based on it.
  • A class encapsulates data (attributes) and behavior (methods) that objects of that class will have.

What is an Object?

  • An object is an instance of a class.
  • Objects are created based on the class blueprint.
  • Each object has its own unique data and can perform actions defined in the class.
Figure 1.A class is a blueprint, and an object is an instance created based on the class blueprint.

Creating Custom Classes

Now, let’s see how to create our own classes in Java.

public class Car {
    // Instance variables (attributes)
    String brand;
    String model;
    int year;

    // Constructor
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    // Method to display car information
    public void displayInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
}

In this example, we’ve defined a Car class with attributes (brand, model, year) and a constructor to initialize these attributes. We also have a displayInfo method to print car information.

Creating Objects

Let’s create objects of the Car class:

public class Main {
    public static void main(String[] args) {
        // Creating car objects
        Car car1 = new Car("Toyota", "Camry", 2022);
        Car car2 = new Car("Honda", "Civic", 2021);

        // Calling the displayInfo method
        car1.displayInfo();
        car2.displayInfo();
    }
}

In this example, we’ve created two Car objects (car1 and car2) and called the displayInfo method to display their information.

Instance Variables and Methods

  • Instance variables (attributes) store data specific to each object.
  • Methods define the behavior of objects.

Accessing Instance Variables and Methods

You can access instance variables and methods using the dot notation:

car1.brand = "Ford"; // Updating the brand attribute
car1.displayInfo(); // Calling the displayInfo method

Pop Quiz

Quiz 1: What is the purpose of a class in Java?

  1. To define a method in Java.
  2. To store and manage data during program execution.
  3. To initialize the attributes of an object when it is created.
  4. To create an instance of a class.

Quiz 2: What is an object in Java?

  1. A blueprint or template for creating classes.
  2. An instance of a class.
  3. A method that initializes class attributes.
  4. An access modifier for class members.

Quiz 3: What is the purpose of a constructor in Java?

  1. To define a class in Java.
  2. To create an instance of a class.
  3. To initialize the attributes of an object when it is created.
  4. To perform mathematical calculations in Java programs.

Quiz 4: Which of the following is NOT an example of an instance variable in a class?

  1. The number of objects created from the class.
  2. The class's name.
  3. The height of a person (in a class representing people).
  4. The name of a book (in a class representing books).

Quiz 5: How is an object different from a class in Java?

  1. An object is a blueprint for creating classes.
  2. An object is an instance of a class.
  3. An object is used to define methods in Java.
  4. An object is a data type in Java.

Answers:

  1. B
  2. B
  3. C
  4. B
  5. B

Homework

  1. Create a class named Student with attributes name, age, and major. Include a constructor and a method to display student information.
  2. Create two Student objects and display their information.

Class 4: Constructors, Access Modifiers, and Method Overloading

Class Inheritance Class inheritance in Java allows you to create a new class (subclass or child class) that inherits attributes and behaviors from an existing class (superclass or parent class). Subclasses can extend and specialize the functionality of the superclass, promoting code reusability and creating a hierarchical relationship between classes.

Figure 2.Class inheritance in allows you to create a new class that inherits attributes and behaviors from an existing class.

Constructors

In the previous class, we learned about creating custom classes and objects. Now, let’s explore constructors, access modifiers, and method overloading to enhance our understanding of classes and objects.

What is a Constructor?

  • A constructor is a special method that is called when an object is created.
  • It is used to initialize the object’s attributes and perform any setup needed.

Default Constructor

If you don’t provide a constructor for your class, Java automatically provides a default constructor with no arguments. However, you can create your own constructors to customize object initialization.

public class Student {
    String name;
    int age;

    // Default constructor
    public Student() {
        name = "Unknown";
        age = 0;
    }
}

Parameterized Constructor

You can create parameterized constructors to allow for custom initialization when creating objects.

public class Student {
    String name;
    int age;

    // Parameterized constructor
    public Student(String n, int a) {
        name = n;
        age = a;
    }
}

Access Modifiers

Access modifiers control the visibility and accessibility of class members (attributes and methods). There are four types of access modifiers in Java:

  • public: The member is accessible from any other class.
  • private: The member is only accessible within the same class.
  • protected: The member is accessible within the same class and its subclasses.
  • default (no modifier): The member is accessible only within the same package.
public class Person {
    public String name;
    private int age;
    protected String address;
    String email; // Default access modifier
}

Method Overloading

Method overloading allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to call based on the number and types of arguments.

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

    public double add(double a, double b) {
        return a + b;
    }
}

In this example, we have two add methods—one for integers and one for doubles. Java will choose the appropriate method based on the argument types.

Pop Quiz

Quiz 1: What is the default access modifier for class members in Java if no modifier is specified?

  1. public
  2. private
  3. protected
  4. default (package-private)

Quiz 2: Which access modifier allows a class member to be accessible only within the same class?

  1. public
  2. private
  3. protected
  4. default (package-private)

Quiz 3: What is method overloading in Java?

  1. It is a way to create multiple copies of a method within the same class.
  2. It allows a method to have multiple names.
  3. It allows a class to have multiple constructors with the same parameters.
  4. It allows a class to have multiple methods with the same name but different parameters.

Quiz 4: Which keyword is used to call a constructor of the superclass in Java?

  1. super
  2. this
  3. extends
  4. inherits

Quiz 5: What is the purpose of a parameterized constructor in Java?

  1. To define a class in Java.
  2. To create an instance of a class.
  3. To initialize the attributes of an object when it is created.
  4. To perform mathematical calculations in Java programs.

Answers:

  1. D
  2. B
  3. D
  4. A
  5. C

Homework

  1. Create a class named Book with attributes title, author, and year. Include both default and parameterized constructors. Also, create a method to display book information.
  2. Overload the method to display book information so that it can handle books with or without an author.

That’s it for Class 4! Next, we’ll explore more advanced concepts, including inheritance and polymorphism.