Unit 5 Homework
Unit 5
- Creating a Class, describe Naming Conventions
- Constructor
- Accessor Methods
- Mutator (Modifier) Method (Setter)
- Access modifiers
- This keyword
- Standard Methods
// creating a class
class MyClass {
}
class MyClass {
int prop1;
int prop2;
// Constructor here
public MyClass (int prop1input, int prop2input) {
// setting properties using this to reference prop1 & prop2 of the object
this.prop1 = prop1input;
this.prop2 = prop2input;
}
public static void main (String[] args) {
MyClass obj = new MyClass(1, 2);
}
}
MyClass.main(null);
class MyClass {
int prop1;
int prop2;
// Constructor here
public MyClass (int prop1input, int prop2input) {
// setting properties using this to reference prop1 & prop2 of the object
this.prop1 = prop1input;
this.prop2 = prop2input;
}
// getter allows outside class to access prop1
public int getProp1() {
return this.prop1;
}
public static void main (String[] args) {
MyClass obj = new MyClass(1, 2);
// using getter to access prop1
System.out.println(obj.getProp1());
}
}
MyClass.main(null);
// always public void
// setVariable (naming convention)
// parameter type must match type of instance variable being modified
public void setVariable(String variable){
this.variable = variable;
}
class MyClass {
// prop1 cannot be directly accessed
private int prop1;
// prop2 can be directly accessed
public int prop2;
// Constructor here
public MyClass (int prop1input, int prop2input) {
// setting properties using this to reference prop1 & prop2 of the object
this.prop1 = prop1input;
this.prop2 = prop2input;
}
// getter allows outside class to access prop1
public int getProp1() {
return this.prop1;
}
// setter allows outside class to set prop1
public void setProp1 (int propVal) {
this.prop1 = propVal;
}
public static void main (String[] args) {
MyClass obj = new MyClass(1, 2);
// would throw error
// obj.prop1 = 10;
// works (because public)
obj.prop2 = 11;
System.out.println(obj.prop2);
}
}
MyClass.main(null);
// method header always stays the same
// always returns string
// no parameters
public String toString(){
}
public boolean equals (Object obj)
// This method checks if some other Object
// passed to it as an argument is equal to
// the Object on which it is invoked.
public int hashCode()
// This method returns the hash code value
// for the object on which this method is invoked.