CSC125: Principles of Software Development - Day 11 Notes

CSC125: Principles of Software Development - Day 11
Course Philosophy and Support
  • Student Experience: Every Computer Science student, including the instructor, began their journey without immediately grasping concepts. This is a normal part of the learning process.

  • Instructor's Role: The instructor's primary job is to facilitate understanding, with a strong belief in every student's ability to succeed.

  • Commitment to Teaching: The instructor is passionate about teaching and helping students learn, but students must communicate when they need assistance.

  • Seeking Help: Avoid spending excessive hours struggling to understand material independently online. Instead, schedule office hours appointments with the instructor for personalized help.

Non-Static Methods: Understanding Implicit Parameters
  • Previous Claim Refinement: Earlier instruction stated, "Every method* has an implicit parameter." This claim is now refined to be more precise.

  • Corrected Claim: "Every non-static method has an implicit parameter."

  • Definition of Non-Static: A "non-static" method is any method that does not include the static keyword in its declaration.

  • Current Focus: We are now prepared to discuss and clearly understand the fundamental differences between static and non-static variables and methods.

Static vs. Non-Static Members
  • Non-Static Members (Variables and Methods):

    • Association: Associated directly with an object.

    • Access Requirement: An object instance is required to access a non-static variable or method.

    • Example Representation: A Student class can have non-static methods and non-static variables that belong to individual Student objects.

  • Static Members (Variables and Methods):

    • Association: Associated directly with the class itself, not an individual object.

    • Access Requirement: Only the class name is needed to access a static variable or method; no object instance is required.

    • Example Representation: A Student class can also contain static variables and static methods that belong to the Student class as a whole.

The Math Class: An Example of Static Members
  • Illustrative Class: The Math class, part of the Java Class Library, serves as a prime example of a class that exclusively contains static variables and static methods.

  • Static Fields (Variables): Within the Math class, you can find static variables like E (Euler's number) and PI (the mathematical constant pi).

  • Static Methods: The Math class also contains numerous static mathematical functions (e.g., max(), sqrt()).

Accessing Static Variables and Methods
  • Accessing Static Variables: To access a static variable, use the class name, followed by a dot (.), and then the variable name.

    • Syntax: ClassName.variableName

    • Example (Accessing PI):
      java public class Driver { public static void main( String[] args ) { double x; x = Math.PI; // Accessing the static variable PI from the Math class System.out.println(x); } }

    • Reasoning: This approach is used because the variable is associated with the class, not an object, so the class name is the appropriate identifier.

  • Accessing Static Methods: To access a static method, use the class name, followed by a dot (.), and then the method name with its arguments.

    • Syntax: ClassName.methodName(arguments)

    • Example (Accessing sqrt()):
      java public class Driver { public static void main( String[] args ) { double x = 17.0; x = Math.sqrt(x); // Accessing the static method sqrt() from the Math class System.out.println(x); } }

    • Reasoning: Similar to static variables, static methods are tied to the class, necessitating access via the class name.

Reasons for Using Static Variables
  • Reason #1: Defining Constant Values

    • Purpose: Static variables are commonly used to define constant values that all objects within a class, or even other classes, need to know and utilize.

    • Example: public static double MAX_GPA = 4.0;

    • Naming Convention: Constants should always be capitalized (e.g., MAX_GPA).

    • Issue with Non-Static Constants: If a constant were defined as non-static, each object constructed from the class would store its own copy of that constant (e.g., 4.04.0 for MAX_GPA in every Student object). This leads to unnecessary memory wastage.

    • Benefit of Static Constants: When a variable is static, it exists only once within the class, acting as a single, shared value for all objects and other parts of the program that access it. This conserves memory.

  • Reason #2: Tracking Summary Information

    • Purpose: Static variables are useful for keeping track of aggregated or summary information about constructed objects, such as counts, minimums, maximums, or averages.

    • Example:
      java public class Student { public static int numStudents = 0; public Student( ... ) { // ... constructor logic numStudents++; // Increment the static counter each time a Student object is created } }

    • Issue with Non-Static Summary Variables: If a variable tracking summary information (like numStudents) were non-static, each object would have its own independent counter (e.g., each Student object would have numStudents = 1, not a global count).

    • Benefit of Static Summary Variables: A static variable for summary information exists only once in the class, effectively behaving like a global variable for that class. It allows for a single, centralized way to track collective data across all instances of the object.

Reasons for Using Static Methods
  • Core Purpose of Objects: An object's fundamental purpose is to encapsulate and bundle together related data (member variables) and the methods that operate on that data.

  • Non-Static Methods:

    • Dependency: A method should be defined as non-static if its operation inherently depends upon or is tied to the related data (the state) of a specific object instance.

    • Example: A canGraduate(int currYear) method in a Student class would be non-static because its behavior determined by evaluating the gpa and gradYear of that particular Student object.
      java public class Student { public boolean canGraduate( int currYear ) { if( gpa > 2.0 && gradYear == currYear ) { return true; } else { return false; } } }

  • Static Methods:

    • Dependency: A method should be defined as static if its operation does not depend upon, or is not tied to, the related data (the state) of any specific object instance of its class.

    • Example: The max(int val1, int val2) method in the Math class is static because it simply compares two input values and returns the greater one. Its operation does not rely on the internal state of a Math "object."
      java public class Math { public static int max( int val1 , int val2 ) { if( val1 > val2 ){ return val1; } else { return val2; } } }

Avoiding "Magic Numbers" with Constants
  • Bad Programming Practice: It is considered poor programming practice to embed "magic numbers" (unexplained numerical literals) directly within methods.

    • Example: In a canGraduate method, directly using 2.0 (e.g., if( gpa > 2.0 )) is a magic number.

  • Solution: Replacing with Static Constants: Utilize static constants to replace magic numbers.

    • Example: Instead of gpa > 2.0, use gpa > MIN_GPA_TO_GRADUATE where MIN_GPA_TO_GRADUATE is a public static final double.
      java public class Student { public static double MIN_GPA_TO_GRADUATE = 2.0; public boolean canGraduate( int currYear ) { if( gpa > MIN_GPA_TO_GRADUATE && gradYear == currYear ) { return true; } else { return false; } } }

  • Reasons for Using Constants over Magic Numbers:

    1. Improved Readability and Understanding: Constants provide meaningful names that explain the purpose of a value, making the code easier to read and comprehend for anyone reviewing it.

    2. Easier Maintenance and Modification: If the constant value needs to change (e.g., MIN_GPA_TO_GRADUATE changes from 2.02.0 to 2.52.5), it only needs to be updated in one place (the constant definition). Without constants, every instance of the magic number would need to be located and changed, which is error-prone and time-consuming.