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
statickeyword in its declaration.Current Focus: We are now prepared to discuss and clearly understand the fundamental differences between
staticandnon-staticvariables 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
Studentclass can havenon-staticmethods andnon-staticvariables that belong to individualStudentobjects.
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
Studentclass can also containstaticvariables andstaticmethods that belong to theStudentclass as a whole.
The Math Class: An Example of Static Members
Illustrative Class: The
Mathclass, part of the Java Class Library, serves as a prime example of a class that exclusively containsstaticvariables andstaticmethods.Static Fields (Variables): Within the
Mathclass, you can findstaticvariables likeE(Euler's number) andPI(the mathematical constant pi).Static Methods: The
Mathclass also contains numerousstaticmathematical functions (e.g.,max(),sqrt()).
Accessing Static Variables and Methods
Accessing Static Variables: To access a
staticvariable, use the class name, followed by a dot (.), and then the variable name.Syntax:
ClassName.variableNameExample (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
staticmethod, 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:
Staticvariables 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., for
MAX_GPAin everyStudentobject). 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:
Staticvariables 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., eachStudentobject would havenumStudents = 1, not a global count).Benefit of Static Summary Variables: A
staticvariable 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-staticif 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 aStudentclass would be non-static because its behavior determined by evaluating thegpaandgradYearof that particularStudentobject.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
staticif 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 theMathclass is static because it simply compares two input values and returns the greater one. Its operation does not rely on the internal state of aMath"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
canGraduatemethod, directly using2.0(e.g.,if( gpa > 2.0 )) is a magic number.
Solution: Replacing with Static Constants: Utilize
staticconstants to replace magic numbers.Example: Instead of
gpa > 2.0, usegpa > MIN_GPA_TO_GRADUATEwhereMIN_GPA_TO_GRADUATEis apublic 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:
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.
Easier Maintenance and Modification: If the constant value needs to change (e.g.,
MIN_GPA_TO_GRADUATEchanges from to ), 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.