Read about:
Objects: http://www.learnjavaonline.org/en/Objects
(Notice that they didn't add the keyword "public". You should, though.)
Methods: http://www.learnjavaonline.org/en/Functions
Finally, nearly at the end of the road with these tutorials! Sadly though, these are my least favorite parts about teaching Java programming. Lets go over Objects and Methods.......
Do you remember way back in set up where I explained that a class is a blueprint for making objects and other functions? Well for this lesson, we are gonna have to make two new, SEPARATE classes. This is ESSENTIAL in robotics programming because we have to call in many functions to run pneumatics, motors, and other electrical stuff.
Consider the following Person class:
public class Person{
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public void grow() {
age ++; //increment the age
}
}
A class usually has these components:
Private instance fields are to store values in an object.
A constructor is to construct an object. The values of instance fields can be assigned in the constructor.
Methods, or functions, are to process stuff when it is called.
Optionally, to make the object more useful, you can also have:
public static final int ADULT = 18;
A class can:
(We'll learn about these later)
"Getters": They just return the value of instance fields.
public int getAge(){
return age;
}
"Setters": You put in the parameter(s), and it will change the instance field.
public void setAge(int age){
this.age=age;
}
When you want to refer to the instance variable instead of the parameter variable, use this.___ so the compiler will find the right one.
toString(): Return a string that represents the object
//in the object class
public String toString(){
return "My name is "+name;
}
//when you use it
Person p = new Person(16,"Bob");
System.out.println(p); //same as calling p.toString(), it will print out "My name is Bob"
Move on to the unit test to see exercises on this!
Created: Luke 4/7/18
Updated: Dexin 4/21/18