Skip to content

CSC203 Midterm 1 Study Guide

1. Basic Classes and Objects

Class Structure

  • A class is a blueprint for objects that contains:
    • Instance variables (object state)
    • Methods (object behavior)
    • Constructors (object initialization)
    • Private variables for encapsulation

Constructors

  • Special methods called when creating new objects using new
  • Must have the same name as the class
  • Can be overloaded (multiple constructors with different parameters)
  • Default constructor is provided only if no other constructors are defined
  • Use this keyword to refer to instance variables

Example:

public class Cat {    
    private String name;    
    private int age;    

    // Constructor    
    public Cat(String name, int age) {        
        this.name = name;        
        this.age = age;    
        }    
        // Default constructor    
        public Cat() {        
            this.name = "Unknown";        
            this.age = 0;    
            }
}

Access Modifiers

  • public: Accessible from any class
  • private: Only accessible within the class
  • protected: Accessible within package and by subclasses
  • Default (no modifier): Only accessible within package

2. Methods

Instance vs Static Methods

  • Instance methods:
    • Can access instance variables
    • Called on object instances
    • Have implicit this parameter
    • Example: cat.getName()
  • Static methods:
    • Cannot access instance variables directly
    • Called on the class itself
    • No this parameter
    • Example: Math.abs()

Getters and Setters

  • Used to control access to private instance variables
  • Follow naming convention: getName(), setName()
  • Encapsulation best practice

Example:

public class Cat {    
    private String name;    

    public String getName() {        
        return name;    
    }    

    public void setName(String name) {        
        this.name = name;    
    }
}

3. Object Class Methods

toString()

  • Returns string representation of object
  • Automatically called when object is printed or concatenated
  • Best practice to override for custom classes

Example:

@Override
public String toString() {    
    return "Cat{name='" + name + "', age=" + age + "}";
}

equals()

  • Defines object equality
  • Must override for custom object comparison
  • Important for collections (HashSet, HashMap)
  • Must be consistent with hashCode()

Example:

@Override
public boolean equals(Object o) {    
    if (this == o) return true;    
    if (!(o instanceof Cat)) return false;    
    Cat cat = (Cat) o;    
    return age == cat.age &&
           Objects.equals(name, cat.name);
}

hashCode()

  • Returns integer hash value for object
  • Must be consistent with equals()
  • Used by hash-based collections
  • Common implementation uses prime numbers

Example:

@Override
public int hashCode() {    
    int hash = 1;   
    hash = 31 * hash + (name == null ? 0 : name.hashCode());    
    hash = 31 * hash + age;    
    return hash;
}

4. Inheritance

Key Concepts

  • Allows classes to inherit properties and methods
  • Uses extends keyword
  • Java only allows single inheritance
  • All classes implicitly extend Object
  • Use super to call parent constructor/methods

Example:

public class Animal {    
    protected String name;   

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

public class Cat extends Animal {    
    private int lives;  

    public Cat(String name, int lives) {        
        super(name);  // Call parent constructor        
        this.lives = lives;    
        }
}

Method Overriding

  • Child class can provide new implementation of parent method
  • Must use @Override annotation
  • Method signature must match exactly
  • Cannot reduce visibility
  • Cannot override final methods

5. Interfaces

Key Concepts

  • Define contract for implementing classes
  • Can have multiple interfaces
  • All methods are public by default
  • Variables are public static final by default
  • Uses implements keyword

Example:

public interface Animal {    
    String vocalize();    
    void move();
}

public class Cat implements Animal {    
    @Override    
    public String vocalize() {        
        return "Meow";    
    }    

    @Override    
    public void move() {        
        System.out.println("Cat is walking");    
    }
}

Default Methods in Interfaces

  • Can provide default implementation
  • Implementing classes can override if needed
  • Helps with backward compatibility
public interface Animal {    
    default void sleep() {        
        System.out.println("Sleeping...");    
    }
}

6. Type Casting

Rules

  • Upcasting (child to parent): Always safe, implicit
  • Downcasting (parent to child): Requires explicit cast, may throw ClassCastException
  • Interface casting follows same rules
  • Use instanceof to check before downcasting

Example:

Animal animal = new Cat();  // Upcast (implicit)
if (animal instanceof Cat) {    
    Cat cat = (Cat) animal;  // Downcast (explicit)
}

Study Tips

  1. Practice writing common method overrides (equals, hashCode, toString)
  2. Understand difference between instance and static methods
  3. Draw class hierarchies to visualize inheritance relationships
  4. Practice implementing interfaces
  5. Write code examples for type casting scenarios
  6. Understand when to use private variables with getters/setters vs public variables

Common Pitfalls to Avoid

  1. Forgetting to call super() in subclass constructors
  2. Not making fields private (poor encapsulation)
  3. Inconsistent equals() and hashCode() implementations
  4. Using == instead of equals() for object comparison
  5. Trying to access non-static members from static methods
  6. Forgetting to handle null cases in equals() method

Key UML Concepts

  1. Class name in top compartment
  2. Fields in middle compartment
    • + public
      • private
    • # protected
  3. Methods in bottom compartment
  4. Inheritance shown with solid arrow pointing to parent
  5. Interface implementation shown with dashed arrow