// import existing packages
import org.code.neighborhood.*;
// Defining a class called MyNeighborhood
public class MyNeighborhood {
public static void main(String[] args) {
// creating an instance of PainterPlus() with variable name myBackgroundPainter
PainterPlus myPainterPlus = new PainterPlus();
// Running turnRight() method from PainterPlus instance
myPainterPlus.turnRight();
}
}
// Creating subclass of PainterPlus which inherits attributes from superclass Painter
public class PainterPlus extends Painter {
public PainterPlus() {
super();
}
// Defining public turnRight() method with no return types in PainterPlus class
public void turnRight() {
turnLeft();
turnLeft();
turnLeft();
}
}
Key Learnings
- Creating and using objects
- use "public class" to create a class
- Within the class, use "public" to define methods that can used outside and inside the class and "private" to define methods that can only be used within the class.
- "void" is used to specify that the respective method does not return anything
- "static" means that no matter how many times the method is initialized, it will only be created once, therefore all instances created shares a single field. It belongs to itself instead of an instance.
- use "[Class Name] [Variable Name] = new [Class Name] ();" to create new object of the specified class
- use period (.) after object variable to use its method
- use "public class" to create a class
- Extend
- "extends" makes the class defined before it a subclass of the superclass (an already defined class you are extending) that is defined after "extends"
- The subclass inherits all of the superclass's attributes