Objects and Classes
ISYS350
Instructor: Lei Jin
Defining Class Variables and Methods: static
public class Math public class TestMath
{ public final static double PI=3.14159; { public static void main(String[] args)
… {System.out.println(Math.PI);
public static double sqrt(double a)
System.out.println(Math.sqrt(32));
{…}
public static double random() System.out.println(Math.random()*100);
{…} }
} }
•Class variables(static variables) belongs to the class, not an individual object of
the class.
•All objects of the same class have the same value for its class variable. if one
object changes the value of a static variable, the value of all object are affected.
•Static variables should be initialized when they are declared.
•Static methods cannot use instance variables or call instance methods.
Access Class Variables and Invoke Class
Methods
• Access class variables
Classname.variableName
Math.PI
Color.black
• Calling class methods
ClassName.methodName(argumentList); or
ClassName.methodName();
Math.random();
MyInput.readInt();
You don’t have to create an object of the class to
access class variables or class methods !!!
Class Design Principles
• Always keep data private - enforce data encapsulation
• Always initialize data;
• Don’t use too many basic types in a class, instead,
organize them into a new class if necessary
private String street;
private string city; class Address
private string state;
private int zip;
• Break up classes with too many responsibilities
CardDeck CardDeck + Card
• Make the names of your classes and methods reflect
their responsibilities
class BillingAddress; setSalary();