Instance Variables:
- Located outside of any method
- Represents instance data
- Allows data to be modified and accessed by any method in the class
- Data is different depending on the object
Visibility Modifiers:
Public:
Allows external classes to modify instance variables
Private and Encapsulation:
Encapsulation: The idea that only a class should be able to modify its own instance variables
- Private variables enforce Encapsulation, only being able to be modified by the class that they are apart of
public class example {
private int a;
}
Testing Objects:
You can create a main method and create objects inside of a class in order to check for errors
public class test {
private int a;
private bool b;
//Test Method
public static void main(String[] args) {
testObject = new test();
}
}
Constructors:
Create new objects and gives value to their instance variables
Default Constructors:
Every class has a default constructor and gives default values based off the data type:
Type: | Default Value |
---|---|
Numeric Primitive Types | 0 |
boolean | false |
class(object) | null |
Writing Custom Constructors:
- Allows us to input custom values into instance variables
- Is public in order to allow other classes to create objects of this class
- Only method that doesn’t have a return type
- Name is the same as the class
public class exampleC {
private int myNum;
private bool allowed;
//Constructor
public example(int newNum, bool choice) {
myNum = newNum;
allowed = choice;
}
}
Calling Constructors:
Once a Custom Constructor is created, the default one becomes unavailable
//Using class exampleC from above
//Code below is in another class/file
exampleC myExample = new exampleC(); //Default Constructor, values are 0 and false
exampleC myExample2 = new exampleC(5, true); //Custom Constructor, value are 5 and true
Methods:
Instance Methods:
- Not static, unlike normal methods
- Can only be called on an object of the method’s class
- Interface: The collective public methods of a class
public int instanceMethod() {
}
Helper Method:
- Private and used internally by one or more other methods
- Improves modularity and Code reusability
public int instanceMethod() {
//Helper Method
private static void HelperMethod(){
}
}
Static Variables, Constants, and Methods:
A static method can't directly access a non-static member
The keyword static makes a constant/variable/method shared among all objects of a class
- Saves memory
- Stores data between objects
- Use when you don’t want to store data for only a specific instance
Math.random:
The Math.random() method is used to return a random number within a given range
//Expression
(int)(Math.random() * ((max - min) + 1)) + min;
//max is the highest possible generated number
//min is the lowest possible generated number;