View on GitHub

Notes

reference notes

Programmer-Defined Classes

The following Java code demonstrates the use of programmer-defined classes:

class BicycleRegistration {
    public static void main(String[] args) {
        Bicycle bike1, bike2;
        String owner1, owner2;

        bike1 = new Bicycle( ); // Create and assign values to bike1
        bike1.setOwnerName("Adam Smith");

        bike2 = new Bicycle( ); // Create and assign values to bike2
        bike2.setOwnerName("Ben Jones");

        owner1 = bike1.getOwnerName( ); // Output the information
        owner2 = bike2.getOwnerName( );
        
        System.out.println(owner1 + " owns a bicycle.");
        System.out.println(owner2 + " also owns a bicycle.");
    }
}

The Definition of the Bicycle Class

class Bicycle {
    // Data Member
    private String ownerName;
    
    // Constructor: Initializes the data member
    public Bicycle( ) {
        ownerName = "Unknown";
    }
    
    // Returns the name of this bicycle's owner
    public String getOwnerName( ) {
        return ownerName;
    }
    
    // Assigns the name of this bicycle's owner
    public void setOwnerName(String name) {
        ownerName = name;
    }
}

Multiple Instances

Once the Bicycle class is defined, we can create multiple instances:

Bicycle bike1, bike2;

bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( );
bike2.setOwnerName("Ben Jones");

This code demonstrates creating instances of the Bicycle class, setting owner names, and displaying ownership information.

main class ( ):

bike1.setOwnerName("Adam Smith");

Bicycle class ( ):

public void setOwnerName(String name)
{
 ownerName = name;
}

Data Member Declaration

To declare a data member in Java, you use the following syntax:

<modifiers> <data type> <name>;

Method Declaration

To declare a method in Java, you use the following syntax:

<modifier> <return type> <method name>(<parameters>) {
    <statements>
}

Constructor

A constructor is a special method executed when a new instance of the class is created. The constructor has the following syntax:

public <class name>(<parameters>) {
    <statements>
}

For example, in the context of a Bicycle class:

public Bicycle( ) {
    ownerName = "Unknown";
}

The Bicycle constructor initializes the ownerName data member to a default value when a new Bicycle instance is created.

The Program Structure and Source Files

In Java, each class definition is typically stored in a separate source file. For example, if you have two classes, Bicycle and Account, each class will be defined in its own source file.

Defining and Using Multiple Classes

In Java, you can define and use multiple classes within a program. Below is an example program that uses both the Bicycle and Account classes:

class SecondMain {
    // This sample program uses both the Bicycle and Account classes
    public static void main(String[] args) {
        Bicycle bike;
        Account acct;
        
        String myName = "Jon Java";
        
        bike = new Bicycle( );
        bike.setOwnerName(myName);
        
        acct = new Account( );
        acct.setOwnerName(myName);
        acct.setInitialBalance(250.00);
        
        acct.add(25.00);
        acct.deduct(50);
        
        // Output some information
        System.out.println(bike.getOwnerName() + " owns a bicycle and");
        System.out.println("has $" + acct.getCurrentBalance() + " left in the bank");
    }
}

The program defines a SecondMain class and uses both the Bicycle and Account classes to demonstrate their functionality.

Account Class

class Account {
    private String ownerName;
    private double balance;
    
    public Account( ) {
        ownerName = "Unassigned";
        balance = 0.0;
    }
    
    public void add(double amt) {
        balance = balance + amt;
    }
    
    public void deduct(double amt) {
        balance = balance - amt;
    }
    
    public double getCurrentBalance( ) {
        return balance;
    }
    
    public String getOwnerName( ) {
        return ownerName;
    }
    
    public void setInitialBalance(double bal) {
        balance = bal;
    }
    
    public void setOwnerName(String name) {
        ownerName = name;
    }
}

The Account class has methods for managing an account’s balance, owner’s name, and related operations. The example demonstrates creating an Account instance and performing various operations on it.

This allows you to see how Java programs can use multiple classes to organize and manage different aspects of your application.

Changing Any Class to a Main Class

In Java, you can define the main method in any class to make that class the entry point for a program. Here are examples of classes that have the main method defined within them:

CombineBicycle.java

This class defines the Bicycle class and includes a main method for demonstrating the use of the Bicycle class:

class Bicycle {
    private String ownerName;

    public String getOwnerName( ) {
        return ownerName;
    }

    public void setOwnerName(String name) {
        ownerName = name;
    }

    public static void main(String[] args) {
        Bicycle myBike;
        myBike = new Bicycle( );
        myBike.setOwnerName("Jon Java");
        System.out.println(myBike.getOwnerName() + " owns a bicycle");
    }
}

Computer and Laptop Classes

This example demonstrates two classes, Computer and Laptop, where the main method is defined within the Computer class:

class Laptop {
    Laptop() {
        System.out.println("Constructor of Laptop class.");
    }

    void laptop_method() {
        System.out.println("99% Battery available.");
    }
}

class Computer {
    Computer() {
        System.out.println("Constructor of Computer class.");
    }

    void computer_method() {
        System.out.println("Power gone! Shut down your PC soon...");
    }

    public static void main(String[] args) {
        Computer my = new Computer();
        Laptop your = new Laptop();
        my.computer_method();
        your.laptop_method();
    }
}

In the Computer class, the main method demonstrates the interaction between the Computer and Laptop classes.

By defining the main method within any class, you can make that class the starting point for running a Java program.

Arguments and Parameters

An argument is a value we pass to a method, as demonstrated in the following code:

class Account {
    // ...
    public void add(double amt) {
        balance = balance + amt;
    }
    // ...
}

class Sample {
    public static void main(String[] args) {
        Account acct = new Account();
        // ...

        acct.add(400);
        // ...
    }
    // ...
}
public class DemoMain {
    public static void main(String[] args) {
        Demo demo = new Demo();
        int i = 5;
        int k = 14;
        demo.compute(i, k, 20);
        //demo.compute(i, k, 20.00);
    }
}

public class Demo {
    //public void compute(int i, int j, double x) {
    public void compute(int i, int j, int x) {
        System.out.println(i);
        System.println(j);
        System.println(x);
    }
}

Memory Allocation

When it comes to memory allocation:

Java toString Method

The toString method in Java is utilized to obtain a string representation of an object. Here’s an example using a LibraryCard class:

class LibraryCard {
    // Data Members
    // Student owner of this card
    private Student owner;
    // Number of books borrowed
    private int borrowCnt;
    // Returns the string representation of this card
    public String toString() {
        return "Owner Name: " + owner.getName() + "\n" +
               " Email: " + owner.getEmail() + "\n" +
               "Books Borrowed: " + borrowCnt;
    }

    public static void main(String[] args) {
        LibraryCard card = new LibraryCard();
        System.out.println(card);
    }
}

The Importance of the toString() Method

Example: Implementation of toString() Method

Here’s an example of the implementation of the toString() method within a LibraryCard class:

class LibraryCard {
    // Data Members
    // Student owner of this card
    private Student owner;
    // Number of books borrowed
    private int borrowCnt;

    // Constructor
    public LibraryCard(){
        owner = null;
        borrowCnt = 0;
    }

    // Number of books checked out
    public void checkOut(int numOfBooks) {
        borrowCnt = borrowCnt + numOfBooks;
    }

    // Get the number of books borrowed
    public int getNumberOfBooks(){
        return borrowCnt;
    }

    // Get the name of the owner of this card
    public String getOwnerName(){
        return owner.getName( );
    }

    // Set the owner of this card to a student
    public void setOwner(Student student) {
        owner = student;
    }

    // Returns the string representation of this card
    public String toString(){
        return "Owner Name: " + owner.getName() + "\n" +
               " Email: " + owner.getEmail() + "\n" +
               "Books Borrowed: " + borrowCnt;
    }
}

Example Usage:

In the Librarian class:

public class Librarian {
    public static void main(String[] args) {
        Student student;
        LibraryCard card1, card2;
        student = new Student( );
        student.setName("Jon Java");
        student.setEmail("jj@javauniv.edu");
        card1 = new LibraryCard( );
        card1.setOwner(student);
        card1.checkOut(3);
        card2 = new LibraryCard( );
        card2.setOwner(student); // the same student is the owner of the second card, too
        System.out.println("Card1 Info:");
        System.out.println(card1.toString() + "\n");
        System.out.println("Card2 Info:");
        System.out.println(card2.toString() + "\n");
    }
}

The this Keyword

The this keyword is used to:

  1. Refer to the current class’s instance variable.
  2. Refer to the current class’s constructor.
  3. Refer to current class methods.

Example:

public class Circle {
    double radius; // instance variable called "radius"
    
    public Circle(double radius) { // Method's argument also called "radius"
        this.radius = radius; // "this.radius" refers to this instance's member variable
        // "this.radius" refers to the member variable, while "radius" resolves to the method's argument.
    }
    // ...
}

Constructors in Java

Handling Initial Balance

Consider the following code:

Account acct;
acct = new Account( );
acct.setInitialBalance(500);
acct.setInitialBalance(300);

Improved Constructor

An improved constructor can solve these problems:

public Account(double startingBalance) {
    ownerName = "Unassigned";
    balance = startingBalance;
}
Account acct;
acct = new Account(25.00);

Constructor Purpose

Information Hiding and Visibility Modifiers

Data Members Should Be private

Sample Program (Visibility Modifiers)

class AccountVer2 {
    // Data Members
    private String ownerName;
    private double balance;

    // Constructor
    public AccountVer2(String name, double startingBalance ) {
        ownerName = name;
        balance = startingBalance;
    }

    public void add(double amt) {
        balance = balance + amt;
    }

    public void deduct(double amt) {
        balance = balance - amt;
    }

    public double getCurrentBalance( ) {
        return balance;
    }
}

Why declaring data members public is considered bad design:

Guideline for Visibility Modifiers

Access Modifiers

Class Constants

Local Variables

Example:

public double convert(int num) {
    double result;
    result = Math.sqrt(num * num);
    return result;
}

Calling Methods of the Same Class