Java Review

CSC Data Structures and Algorithms

Brian-Thomas Rogers

University of Illinois Springfield

College of Health, Science, and Technology

Classes and Objects

Objects

  • An object is a program construct that
    • Contains data
    • Performs certain actions
  • The actions are called methods
  • The actions interact to form the solution to a problem

Classes

  • A class is the type or kind of object
  • Objects of the same class have
    • The same kinds of data
    • The same methods
  • A class definition is a general description of
    • What the object is
    • What it can do

Example of a class

Class Outline of an Automobile

Instantiation of the Class

Three instances of the automobile class

Defining a Java Class

  • Syntax Form
<access modifier> Class <class name>
{
  //Data fields
  //Method Definitions
}
  • Example
public class Name {
  private String first;
  private String last;
  //<Method definitions>
}

Note

The data fields are set to private so if they are required by other classes then they will require accessor and mutator methods.

Method Definitions

  • Syntax form
<access modifier> <return type> <method name>(<parameter list>)
{
  <method body>
}

General Example

public double f(double m, double x, double b) {
  return m * x + b;
}

This is a public method with name f which returns a double and accepts three double types, m, x, and b and returns the result of \(m * x + b\).

Accessor Methods

  • Useful for data fields which cannot be accessed directly
public String getFirst() {
  return first;
}
  • This is a valued method
  • That value is of type String

Mutator Methods

  • Useful for data fields which cannot be accessed directly
public void setFirst(String firstName) {
  this.first = firstName;
}
  • This is a void method.
  • It returns nothing.

Constructors

  • A special method that
    • Is called when a new object of a class is created
    • Allocates memory for the object
    • Initializes the data fields
  • Syntax form
<access modifier> <class name>(<parameter list>)
{
  <constructor mody>
}

Default Constructor

  • If no constructor is explicitly defined then an implicit constructor is defined
    • The implicit constructor takes no arguments
    • It does nothing more than allow the creation of an object
  • The default constructor can be overridden by explicitly declaring a constructor with no parameters
  • If there exists another constructor which takes parameters and no constructor with 0 parameters then the constructor which takes parameters will become the default constructor

Constructors Continued

  • A class can have several constructors
public class Name {
  private String firstName;
  private String lastName;

  //Default constructor
  public Name() {
    firstName = null;
    lastName = null;
  }

  //Initializes data fields
  public Name(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

Creating an Object of a Class

  • To create an object of a class use the new keyword
  • The new keyword creates an instance by invoking the constructor used

Name joe = new Name();

Name jack = new Name("Jack", "Smith");

Calling Object Methods

  • Given the following
Name joe = new Name();
joe.setFirst("Joseph");
joe.setLast("Brown");
  • "Joseph" and "Brown" are arguments sent to the methods
  • Invocation of methods must have the same number and type of arguments as formal parameters in the declaration

References and Aliases

  • Primitive Types
    • byte, short, int long, float, double, char, boolean
  • All other types are reference or class types
String greeting = "Howdy";
  • greeting is a reference variable
  • When two variables reference the same instance they are aliases
Name jamie = new Name("Jamie", "Jones");
Name friend = jamie;

friend aliases jamie

Passing Arguments

  • Call-by-Value
    • For primitive types, parameter is initialized to value of argument in call
  • Call-by-Reference
    • For class types, formal parameter is initialized to the address of the object in the call
  • Java is Pass-by-Value (Call-by-Value), Dammit!

Passing Arguments

  • Let us add another method giveLastNameTo to the Name class
public class Name {
  private String firstName;
  private String lastName;

  //Methods and constructors

  public void giveLastNameTo(Name child) {
    child.setLast(lastName);
  }
}
  • Now you can give the last name of one Name object to another Name object
Name jamie = new Name("Jamie", "Jones");
Name jane = new Name("Jane", "Doe");
jamie.giveLastNameTo(jane);

Passing Arguments Pictured 1/2

jamie.giveLastNameTo(jane);

Passing Arguments Pictured 2/2

jamie.giveLastNameTo(jane);

Static Fields

  • A data field that does not belong to any one object
  • One instance of that data item exists to be shared by all instances of the class
  • Also called static field, static variable, class variable

Static Methods

  • When a method is defined as static it does not belong to any particular object
  • You can call the static method by using the class name
  • Example: Java’s predefined Math class contains several standard mathematical methods defined as static
    • double root = Math.sqrt(4.2)
  • Static methods cannot call a non-static method!

Main Method

  • The first static method you learned about in Java is the main method
  • The main method is the entry point for a Java executable.
    • When you run a Java program it looks for and runs the main method
    • If no main method exists, nothing happens.
  • The main method is usually placed in a separate class by itself often called a driver class (though does not need to be named Driver).
public class Driver {
  public static void main(String args[]) {
    //Start of program
  }
}

Naming Conventions

  • Start method name with lowercase letter
    • Use verb or action phrase
  • Start class name with Uppercase
    • Use noun or descriptive phrase

Note

Conventions are not hard and fast rules. The Java compiler will not enforce conventions or standards, though, professional developers will judge you.

Packages

  • A Java package is just a directory and the package keyword at the top of the .java file with the name of the directory.
package gameobject;

public class Player {
  //Player definitions
}
  • Multiple related classes can be conveniently grouped into a package
  • Begin each file that contains a class within the package using the same package name.
  • Place all files within a director with same name as the package
  • To use the classes from other classes in a package begin the program with import statements
import gameobject.Player;

The Java Class Library

  • A library is a collection of code that is usable by others
  • Many useful classes have already been declared
  • Example
    • The class Math is part of the package java.lang
      • java is one package and lang is another inside the java package
  • Checkout the following for all the packages and classes available
    • Java 20 API
    • If you are using a version less than 20 then you can Google Java <your version number> API

Composition

Composition

  • Composition is just a fancy term for “What is a class made of?”
    • Also known as a “has a” type relationship
  • When a class has a data field that is an instance of another class
  • Example using an object of type Student

Student class has a Name object and a String object

Generic Types

  • Consider a class with fields that can be of any class type
  • Use a Generic type
    • Follow class name with identifier enclosed in angle brackets
      • I like to call this “diamond notation”
    • public class MyClass <T>
      • The <T> notation defines a generic called T
    • Example on next slide demonstrates use of generic types

Pair Class Using Generics

public class Pair<T> {
  private T first, second;

  public Pair(T first, T second) {
    this.first = first;
    this.second = second;
  }

  public void changeOrder() {
    T temp = first;
    first = second;
    second = temp;
  }

  public String toString() {
    return String.format("(%s, %s)", first, second);
  }
}

Using the Pair Class

Pair<String> fruit = new Pair<>("Banana", "Apple");
System.out.println(fruit); //prints (Banana, Apple)
fruit.changeOrder();
System.out.println(fruit); //prints (Apple, Banana)

Name tweedleDee = new Name("Tweedle", "Dee");
Name tweedleDum = new Name("Tweedle", "Dum");
Pair<Name> couple = new Pair(tweedleDee, tweedleDum);
System.out.println(couple);

Inheritance

Inheritance

  • First define a general base class
  • Then define a more specialized class
    • Add details of the base class
    • Revise details of the base class
  • Advantages
    • Saves work
    • Common properties and behaviors are defined only once for all classes involved
  • Inheritance is known as an “is a” relationship type

Inheritance Tree

A Hierarchy of Classes

Invoking Constructors Within Constructors

  • Constructors usually initialize data fields
  • In a derived class
    • The constructor must call the base class constructor
  • Use of the reserved word super as a name for the constructor of the base class
    • When super is used it must be the first action in the derived constructor definition
    • Must not use the name of the constructor

Private Fields/Methods of Base Class

  • Accessing inherited data fields
    • Not accessible by name within definition of a method from another class - including a derived class
    • Still they are inherited by the derived class
  • Derived classes must use public methods of the base class
  • Private methods in a base class are also unavailable to derived classes
    • But usually not a problem - private methods are used only for utility duties within their class

Protected Access

  • A method or data field modified by protected can be accessed by name only within
    • Its own class definition
    • Any class derived from that base class
    • Any class within the same package

Protected Access

  • Accessibility of elements of a class C determined by the access modifiers

Overriding Methods

  • When a derived class defines a method with the same signature as a base class
    • Same name
    • Same return type
    • Same number, types of parameters
  • Objects of the derived class that invoke the method will use the definition from the derived class
  • It is possible to use super in the derived class to call an overridden method of the base class

Overriding Methods

The method toString in CollegeStudent overrides the method toString in Student

Overloading a Method

  • When the derived class method has
    • The same name
    • The same return type …but…
    • Different number of type of parameters
  • Then the derived class has available
    • The derived class method … and
    • The base class method with the same name
  • Java distinguishes between the two methods due to the different parameters
  • The setStudent method is overloaded in the CollegeStudent class

Multiple use of super

  • Consider a class derived from a base … that itself is derived from a base class
    • All three classes have a method with the same signature
  • The overriding method in the lowest derived class cannot invoke the method in the base class’ base class
    • The construct super.super is illegal!
public class A{
  public String method() {}
}
public class B extends A {
  public String method() {
    //Totally fine
    super.method();
  }
}
public class C extends B{
  public String m() {
    //Totally illegal
    super.super.m();
  }
}

The final Keyword

  • A programmer may wish to specify that a method definition cannot be overridden
  • This is accomplished by use of the modifier final
public final void whatever() {
  ...
}

Multiple Inheritance

  • Some languages allow programmer to derive class C from classes A and B
  • Java does not allow this
    • A derived class can have only one base class
  • Multiple inheritance can be approximated
    • A derived class can have multiple interfaces

Object Types of a Derived Class

  • Given
    • Class CollegeStudent
    • Derived from class Student
  • Then a CollegeStudent object is also a Student object
  • In general an object of a derived class is also an object of the base class
  • You can assign an object of a derived class to a variable of an ancestor type
    • Student amy = new CollegeStudent(); - Valid
    • CollegeStudent cs = new Student(); - Invalid!

The Class Object

  • EVERY class is a descendant of the class Object
  • Object is the class that is the beginning of every chain of derived classes
    • It is the ancestor of every class
    • Even those defined by the programmer
  • Some of the important methods of the Object class are
    • toString
    • equals
    • clone
    • hashCode
  • You usually need to override these

Polymorphism & Encapsulation

Polymorphism

  • At run time, objects of a derived class may be treated as objects of a base class
    • Method parameters
    • Collections or arrays
  • When one method name in an instruction can cause different actions
    • Happens according to the kinds of objects that invoke the methods

Abstract Classes and Methods

  • Abstract classes cannot have objects of their type 1
  • Declare that base class to be abstract
public abstract class Whatever { ... }
  • The designer often specifies methods of the abstract class without a body
public abstract void doSomething();
  • This requires all derived classes to implement this method

Abstract Class Continued

  • We can also declare methods inside an abstract class with method bodies
  • Think of an abstract class like an agreement of two working parties
    • The first party says “Yeah, let me take care of this for you if you would like but you have to take care of this, this, and this”
    • The second party must then agree to the “this, this, and this”
  • Abstract classes must be extended which means a derived class can only extend one Abstract class

Dynamic Binding

  • The process that enables different objects to
    • Use different method actions
    • For the same method name
  • Objects know how they are supposed to act
    • When an overridden method is used…
    • The action is for the method defined in the class whose constructor created the object

Abstract Class Example

//abstract base class
public abstract class Shape { 
  protected String name;

  public Shape(String name) { 
    this.name = name; 
  }

  //abstract method
  //notice, no body is defined.
  public abstract double area();

  public String toString() { 
    return name; 
  }
}

Derived Class of Shape 1/3

//Derived class must implement area
//Since Shape is abstract with 
//abstract method area.
public class Rectangle extends Shape {
  protected double length, width;

  public Rectangle(double length, double width) {
    //Call shape constructor passing 
    //String to name formal parameter
    super("Rectangle");
    this.length = length;
    this.width = width;
  }

  public double area() { 
    return width * length; 
  }
}

Derived Class of Shape 2/3

public class Circle extends Shape {
  protected double radius;

  public Circle(double radius) {
    super("Circle");
    this.radius = radius;
  }

  public double area() {
    return Math.PI * radius * radius;
  }
}

Derived Class of Shape 3/3

public class Triangle extends Shape {
  protected double height, base;

  public Triangle(double height, double base) {
    super("Triangle");
    this.height = height;
    this.base = base;
  }

  public double area() {
    return (base * height) / 2.0;
  }
}

An Array of Shapes

  • Suppose we have an array of shape objects
  • We guarantee that each shape has defined an area method
  • This allows us to have different shape types in the array

Example of Array of Shapes

public class Main {
  public static void main(String args[]) {
    Shape shapes[] = new Shape[3];

    shapes[0] = new Rectangle(3.0, 5.0);
    shapes[1] = new Triangle(1.0, 4.0);
    shapes[2] = new Circle(5);

    double areaSum = 0.0;
    for(int i = 0; i < shapes.length; i++) {
      areaSum += shapes[i].area();
    }

    System.out.println("The total area sum is: " + areaSum);
  }
}

Encapsulation

Encapsulation

  • Hides the fine details of the inner workings of the class
    • The implementation is hidden
    • Often called “information hiding”
  • Part of the class is visible
    • The necessary controls for the class are left visible
    • The class interface is made visible
    • The programmer is given only enough information to use the class

Encapsulation

An automobile’s controls are visible to the driver, but its inner workings are hidden

Encapsulation in Java

An interface provides well-regulated communication between a hidden implementation and a client

Java Interface

  • A program component that contains
    • Public constants (must be final)
    • Signatures for public methods
    • Comments that describe them
  • Begins like a class definition
    • Use the word interface instead of class
public interface SomeInterface {
  public int someMethod1();
  public int someMethod2();
}

Inteface Example

  • Recall class Name from earlier
  • Consider an interface for the class Name
    • Defined on next slide
  • Note
    • Any data fields will be public, final, and static.
    • Interface methods cannot be final.

NameInterface

public interface NameInterface {
  public void setName (String firstName, String lastName);
  public String getName();

  public void setFirst(String firstName);
  public String getFirst();

  public void setLast(String lastName);
  public String getLast();
  public void giveLastNameTo(NameInterface aName);

  public String toString();
}

Implementing an Interface

  • A class that implements an interface must state so at the end of the definition with implements clause
public class MyClass implements SomeInterface
  • The class must implement every method declared in the interface
  • Multiple classes can implement the same interface
  • A class can implement more than one interface
public class C extends B implements Measurable, Runnable

Implementing an Interface

The files for an interface, a class that implements the interface, and the client

An Interface as a Data Type

  • An interface can be used as a data type
//Object passed must be an object of a class
//that implements SomeInterface
public void someMethod(SomeInterface si) {}
  • or …
//The variable can invoke only a certain set of methods
NameInterface myName;

Generic Types Within an Interface

  • Recall the Pair class
  • Consider an interface Pairable
public interface Pariable<T> {
  public void setPair(T firstItem, T secondItem);
}
  • A class that implements this interface could begin with the statement
public class Pair<T> implements Pairable<T>

The Comparable Interface

  • Method compareTo must be implemented for any derived classes
  • compareTo compares two objects, say x and y
  • Programmer should following the convention for compareTo
    • Must return a signed integer
    • Returns a negative if \(x < y\)
    • Returns a zero if \(x == y\)
    • Returns a positive if \(x > y\)

Comparable Interface Example

public class Circle extends Shape implements Comparable<Circle> {
  protected double radius;

  public Circle(double radius) {
    super("Circle");
    this.radius = radius;
  }

  public double area() {
    return Math.PI * radius * radius;
  }

  public int compareTo(Circle other) {
    if(this.radius > other.radius) {
      return 1;
    } else if(this.radius < other.radius) {
      return -1;
    }
    return 0;
  }
}

Extending an Interface

  • Use inheritance to derive an interface from another
  • When an interface extends another
    • It has all the methods of the inherited interface
    • Can include new methods
  • Possible to combine several interfaces into a new interface
    • Not possible with classes

Interface vs. Abstract Class

  • Purpose of interface is similar to purpose of abstract class but …
  • An interface is not a base class
    • it is not a class of any kind
  • Use an abstract base class when
    • You need a method or private data field that classes will have in common
  • Otherwise, use an interface

Named Constants Within an Interface

  • An interface can contain named constants
    • Public data fields initialized and declared as final
  • Consider an interface with a collection of named constants
    • Then derive variety of interface that can make use of these constants