Creating Objects in Code

The guide to everything controls for 1675 members.

Creating Objects in Code

Definitions

NEW FILE Car.java

public class Car {
  String model;
  int miles;
  int speed
  
  //Constructor
  public Car(String mo, int mi, int s) {
    model = mo;
    miles = mi;
    speed = s;
  }
 
  // fullThrottle() method
  public void fullThrottle() {
    System.out.println("The car is going as fast as it can!");
  }

  // setSpeed() method 
  public void setSpeed(int s) {
    speed = s;
  }
  
  // getSpeed() method
  public void getSpeed() {
    System.out.println("The car is going " + speed + " miles per hour.");
  }

NEW FILE Main.java

public class Main {
  // Inside main, call the methods on the myCar object
  public static void main(String[] args) {
    Car myCar = new Car("CRV", 100000, 0);     // Create a myCar object and call the constructor
    myCar.fullThrottle();      // Call the fullThrottle() method
    myCar.setSpeed(70);        // Call the setSpeed() method
    myCar.getSpeed();          // Call the getSpeed() method
  }
}

Brainstorming #1

Exercise #1

NEW FILE Axolotl.java

public class Axolotl {
    // list the variables you chose while brainstorming along with their appropriate types
    int age;
    // int somethingCool;
    // double anotherExampleVariable;
    // boolean underwater;
 
    // constructor method (called automatically when an Axolotl is created)
    public Axolotl(int a) {
       // set the Axolotl's age to the value of parameter "a"
       age = a;
    }

    // write your methods here along with their appropriate return types
    public void growOlder(int years) {
        age = age + years;
    }
    
    // For every variable you add to your class, add a method to print out that value
    public void printAge() {
        System.out.println("Age = " + age);
    }
}

Within “ClassExercise”, create a new file named Main.java and populate it with the following code:

Be sure to change this code to interact with your animal class too!

public class Main {
    public static void main(String[] args) {
        Axolotl ancientJerry = new Axolotl(10000); // Instantiates a new Axolotl within the variable "ancientJerry" and sets its initial age to 10000

        // test out some of the methods you created for your animal:
        ancientJerry.printAge(); // displays the age of ancientJerry
        ancientJerry.growOlder(100); // call to one of the Axolotl class methods to increase age
        ancientJerry.printAge(); // displays the new age of ancientJerry

        // feel free to create more objects using the class:
        Axolotl jerryJunior = new Axolotl(5);  
        jerryJunior.growOlder(100); // jerryJunior is growing up!!
        jerryJunior.printAge();

        ancientJerry.growOlder(-10100);  
        ancientJerry.printAge();
        System.out.println("Ancient Jerry has finally died :[");
    }
}