Introduction to Java Programming and Data Structures

Introduction to Java Programming and Data Structures

  • Chapter 9: Objects and Classes

  • Copyright © 2024 Pearson Education, Inc. All Rights Reserved

Overview of Data Types in Java

  • Data types in Java are not merely predefined; they can be created by programmers to better organize code.

  • Programmers define data types with the term classes.

  • When a variable of a class is created, it is termed as an object of that class.

  • Classes can be conceptualized as types of things.

Object-Oriented Programming (OOP) Concepts

  • Object-oriented programming (OOP) is based on the concept of using objects to program.

  • An object represents identifiable real-world entities. Examples include:

    • A student

    • A desk

    • A circle

    • A button

    • A loan

  • An object has:

    • A unique identity

    • A state, characterized by a set of data fields (properties) with current values

    • Behaviors, defined by a set of methods

Understanding Classes

  • A class functions as a set of instructions (a blueprint) for creating objects.

  • An object is a single instance of a class, with the process of creating an object termed instantiation. Object and instance are interchangeable terms.

  • A Java class consists of:

    • Variables to define data fields

    • Methods to define behaviors

  • A class includes constructors, which are special methods called to create objects from the class.

Functions of Classes

  • Classes provide two core services:

    • Encapsulation/Modularity: Grouping related variables and functions together.

    • Abstraction: Organizing code such that users are presented with a clear, simplified interface, hiding implementation details.

Example Class Definition: Circle

  class Circle {
      /** The radius of this circle */
      double radius = 1.0;
      /** Construct a circle object */
      Circle() { }
      /** Construct a circle object */
      Circle(double newRadius) { radius = newRadius; }
      /** Return the area of this circle */
      double getArea() { return radius * radius * 3.14159; }
  }
  • Data fields: Defined using instance variables (e.g., double radius).

  • Methods: Defined to encapsulate behavior (e.g., getArea()).

  • Constructors: Defined to create objects (e.g., Circle() and Circle(double newRadius)).

UML Class Diagram & Objects

  • An object is characterized by its state and behavior.

  • UML Notation:

    • Example of Circle class:
      Circle radius: double Circle() Circle(newRadius: double) getArea(): double getPerimeter(): double setRadius(newRadius: double): void

    • Instances (objects) of classes shown:

    • circle1: Circle with radius = 1.0

    • circle2: Circle with radius = 25

    • circle3: Circle with radius = 125

Creating Objects from Classes

  • Defining a Class:
    java class classname { //Declare Instance Variables //Declare Constructors //Declare Methods }

  • Constructors:

    • Special methods to construct objects:

      • Example: Circle() { } and Circle(double newRadius) { radius = newRadius; }

    • No-arg Constructor: A constructor with no parameters.

      • Must have the same name as the class.

      • Has no return type, not even void.

      • Invoked using new operator when creating an object.

      • Initialization of objects occurs here.

Instantiation of Objects

  • Creating Objects Using Constructors:

    • Example invocations:

      • new Circle();

      • new Circle(5.0);

Default Constructor

  • A class can exist without explicitly defined constructors.

  • In this case, a default constructor (no-arg constructor with an empty body) is automatically provided by Java if no constructors are explicitly defined by the programmer.

Declaring Object Reference Variables

  • Assigning an object to a reference variable:

    • Syntax: ClassName objectRefVar;

    • Example: Circle myCircle;

Declaring/Creating Objects in a Single Step

  • Syntax for single step declaration and creation:

    • ClassName objectRefVar = new ClassName();

    • Example: Circle myCircle = new Circle();

Instance Variables and Methods

  • Instance Variables: Belong to specific object instances.

  • Instance Methods: Called by instances of the class.

Accessing Object’s Members

  • Referencing Object's Data: objectRefVar.data

    • Example: myCircle.radius

  • Invoking Object's Method: objectRefVar.methodName(arguments)

    • Example: myCircle.getArea()

Trace Code Example (1-7)

  • Trace Code (Example of Object Creation and Assignment):

    • Code: Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100;

    • Output walkthrough of object states and behaviors through 7 steps.

Cautionary Note on Method Invocation

  • Math.methodName(arguments): Used for invoking static methods (like Math.pow(3, 2.5)).

  • Non-static methods (like getArea()) must be invoked from an object, not statically (e.g., myCircle.getArea()).

Reference Data Fields

  • Data fields can be of reference types. Example definition of Student class:
    java public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // gender has default value '\u0000' }

The Null Value

  • If a reference-type data field does not reference any object, it holds a null value.

Default Value for Data Fields

  • Default values determined by data type:

    • Reference type: null

    • Numeric type: 0

    • Boolean type: false

    • Character type: '\u0000'

  • Local variables within methods have no default value.

Difference between Primitive Data Types and Object Types

  • Primitive example:

    • int i = 1;

  • Object example:

    • Circle c; c = new Circle();

    • This creates an object of Circle with default attributes (e.g., radius = 1).

Copying Variables of Primitive Data and Object Types

  • Primitive type assignments copy the value directly, while object type assignments copy the reference:

    • Primitive example:

      • Before: i = 1

      • After: i = 2

    • Object example:

      • c1 = c2 would make both references point to the same object.

Garbage Collection

  • Explained through object reference behavior:

    • If c1 points to the same object as c2, the previous object referenced by c1 becomes garbage and is collected by Java’s Garbage Collector.

  • Tip: Assign null to a reference variable if an object is no longer needed, allowing for cleanup of memory.

Static Variables, Constants, and Methods

  • Static methods: Not tied to specific instances and can be invoked directly from the class.

  • Static variables: Shared across all instances of a class.

  • Static constants: Final variables that are also shared.

  • Use the static modifier to declare static variables, constants, and methods.

Example of Static Class Members Usage

  • Holds an example of a class CircleWithStaticMembers to track instances (e.g., numberOfObjects).

Scope of Variables

  • Local Variable Scope: Begins at declaration, extends until the end of the block. Must be initialized before usage.

  • Instance/Static Variable Scope: Entire class; they have default values.

Visibility Modifiers in Java

  • Control access levels through visibility modifiers:

    • private: Restricts access to class members only.

    • public: Allows access from anywhere.

    • protected: Allows access to classes within the same package.

Importance of Private Data Fields

  • Enhances data protection and eases code maintenance.

Setters and Getters

  • Setters (Mutators): Allow modification of data values (e.g., setRadius(double radius))

  • Getters (Accessors): Allow retrieval of variable values (e.g., getRadius()).

Example of Encapsulation in Classes

  • Shows CircleWithPrivateDataFields which uses private fields and public methods for access: Circle: -radius: double -numberOfObjects: int +Circle() +Circle(radius: double) +getRadius(): double +setRadius(radius: double): void +getNumberOfObjects(): int +getArea(): double

    • The dash (-) indicates private member, while plus (+) indicates public.

The this Keyword

  • this references the current object instance. Used to:

    • Access hidden data fields.

    • Call other constructors within the same class (constructor chaining).

Referencing Hidden Data Fields Using this

  • Demonstration:
    java public class F { private int i = 5; private static double k = 0; void setI(int i) { this.i = i; } static void setK(double k) { F.k = k; } }

  • Example of how setI() sets the value for instances of the class independently.

Calling Overloaded Constructors

  • Example Circle class showing usage of this to invoke constructors and reference properties:
    java public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public Circle() { this(1.0); } public double getArea() { return this.radius * this.radius * Math.PI; } }

  • Importance of this in both constructor overloading and proper instance referencing.