JMU
An Introduction to Classes
with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Classes
Timing of this Discussion
Typical Programming/Software Engineering Sequences
Typical Programming/Software Engineering Sequences (cont.)
The Design and Implementation of Classes
Using Parameters in Methods
Information Hiding
Information Hiding Guidelines
Naming Conventions in Java
Simplified Syntax of a Class

access class class-name
{

[
access [static] type attribute [, attribute]... ;
]...


[
access class-name([type param [, type param]...])
{
}
]


[
access [static] type method([type param [, type param]...])
{
}
]...
}

Simplified Syntax (cont.)
An Example
javaexamples/oopbasics/pf_classes/Purchase.java (Fragment: 0)
public class Purchase {
    // Instance Attributes
    private int productCode, quantity;
    private double price;

    // Constructor
    public Purchase(int code, int q, double p) {
        productCode = code;
        quantity = q;
        price = p;
    }
    
    // Getters
    public double getPrice() {
        return price;
    }

    public int getProductCode() {
        return productCode;
    }
    
    public int getQuantity() {
        return quantity;
    }

    // Setters
    public void setPrice(double p) {
        price = p;
    }
    
    public void setQuantity(int q) {
        quantity = q;
    }
}
        
Interchangeable Terms
A Potentially Confusing Situation
A Potentially Confusing Situation (cont.)
An Example of Disambiguation
javaexamples/oopbasics/pf_classes/Purchase.java (Fragment: Disambiguation)
    public void setProductCode(int productCode) {
        this.productCode = productCode;
    }
        
Java vs. Python - Important Differences
Using Variables in Methods
Using Variables in Methods (cont.)
Class Members
Class Members (cont.)
An Example of Class Attributes
javaexamples/oopbasics/pf_classes/Purchase.java (Fragment: StaticAttributes)
    // Class Attributes
    public static final double MEMBER_REBATE = 0.01;
    public static final double EXECUTIVE_MEMBER_REBATE = 0.05;
        
Class Members (cont.)
Utility Classes
The Main Class
The Main Class (cont.)