03 - 09/01/10 19:29:17 CS 61B: Lecture 3 Wednesday,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
09/01/10 19:29:17 1 03 CS 61B: Lecture 3 Wednesday, September 1, 2010 Today’s reading: DEFINING CLASSES ================ An object is a repository of data. _Fields_ are variables that hold the data stored in objects. Fields in objects are also known as _instance_variables_. In Java, fields are addressed much like methods are, but fields never have parameters, and no parentheses appear after them. For example, suppose that kayla is a Human object. Then kayla.introduce() is a method call, and kayla.age is a field. Let’s write a _class_definition_ for the Human class. class Human { public int age; // The Human’s age (an integer). public String name; // The Human’s name. public void introduce() { // This is a _method_definition_. System.out.println("I’m " + name + " and I’m " + age + " years old."); } } "age" and "name" are both fields of a Human object. Now that we’ve defined the Human class, we can construct as many Human objects as we want. Each Human object we create can have different values of age and name. We might create kayla by executing the following code. Human kayla = new Human(); // Create kayla. kayla.age = 12; // Set kayla’s fields. kayla.name = "Kayla"; kayla.introduce(); // _Method_call_ has kayla introduce herself. -------------- | ---- | --- | age |12| | kayla |.+--->| ---- | ----------- --- | name | -+--+---->| "Kayla" | | ---- | ----------- -------------- a String object a Human object The output is: I’m Kayla and I’m 12 years old. Why is it that, inside the definition of introduce(), we don’t have to write "kayla.name" and "kayla.age"? When we invoke "kayla.introduce()", Java remembers that we are calling introduce() _on_ the object that "kayla" references. The methods defined inside the Human class remember that we’re referring to kayla’s name and age. If we had written "rishi.introduce()", the introduce method would print rishi’s name and age instead. If we want to mix
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 2

03 - 09/01/10 19:29:17 CS 61B: Lecture 3 Wednesday,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online