An Introduction to Java – Part II Ben Lerner An Introduction to Java – Part II
Class Definitions Classes consist of constructors, methods, and fields <modifier> class Person { constructors fields methods }
Constructors and Objects Constructors initialize objects, same name as the class public Person (string name, int age) { … } Objects created using new keyword and the constructor, store reference Person P = new Person(“Michael”, 21);
Fields Fields are the variables that define the attributes of a class string name_; int age_; Constructors initialize an object’s fields public Person (string name, int age) { name_ = name; age_ = age; }
Methods Mutator methods change fields void setAge(int a) { age_ = a; } Inspector methods access fields string getName() { return name;} Constructors are also methods
Parameters Both primitive variables and objects can be passed to methods Parameters are always passed by value Remember that objects in Java are just references to the objects