跳转至

Lecture4 Classes and Objects

1. Object oriented programming

Represent the real world.

  • primitives (int, double, char)
  • objects(String)
Java
public class Baby {
    String name;
    boolean isMale;
    double weight;
    double decibels;
    int numPoops = 0; 

    void poop() {
    numPoops += 1;
    System.out.println(“Dear mother, ”+
    “I have pooped. Ready the diaper.”);
    }
}

// class instance
Baby myBaby = new Baby();

// Class definition
public class [.......]

// Using classes
// class Instances
Baby shiloh = new Baby("Shiloh Jolie-Pitt", true);
Baby knox = new Baby("Knox Jolie-Pitt", true);

// Accessing fields
System.out.println(shiloh.name);

// Calling Methods
shiloh.sayHi() //
  • Class names are Capitalized
  • 1 Class = 1 file
  • Having a main method means the class can be run

2. Primitives vs References

  • Primitive types are basic java types
  • Reference types are arrays and objects

The same as python

3. Static types and methods

Static

  • applies to fields and methods
  • Means the field/method
    • Is defined for the class declaration,
    • Is not unique for each instance

Non-static methods can reference static methods, but not the other way around.

Assignment 4