Classes

  • Classes are blueprints for objects
  • You can create multiple objects from one class and have them inherit properties, making it easy to manage data

In the example below, the class Math has an attribute. Can you name it?

What will the output of this code be?

public class Main {
    int x;
  
    public Main(int y) { // this is the constructor, which sets the value of y
     x = y;
    }
  
    public static void main(String[] args) { // 
      Main myObj = new Main(5);
      System.out.println(myObj.x);
    }
  }

Objects

  • Constructor syntax is "Class objectName = new Class(parameters);"
  • Objects are created from classes using a class constructor

Can you find the constructors in this code?

What would this code print?

public class Main {
    int x = 5;
  
    public static void main(String[] args) {
      Main myObj1 = new Main();  // object 1
      Main myObj2 = new Main();  // object 2
      System.out.println(myObj1.x);
      System.out.println(myObj2.x);
    }
  }

Methods

  • Essentially functions in Java
  • Can declare a method and then call it

Where is the method in this code and what is the output?

public class Main {
    static void myMethod() {
      System.out.println("I was just executed!");
    }
  
    public static void main(String[] args) {
      myMethod();
    }
  }