Class Notes for High School Computer Science
In Java, instance variables are variables that belong to an object.
They are also called fields because they describe the data or characteristics stored inside a class.
private String name;
private int score;
private double balance;
These variables store information that each object needs to remember.
An instance means an object created from a class.
Student s1 = new Student();
Student s2 = new Student();
Here, s1 and s2 are two different instances of the
Student class.
Each object gets its own copy of the instance variables.
public class Student
{
private String name;
private int gradeLevel;
private double gpa;
}
| Instance Variable | Data Type | What It Stores |
|---|---|---|
name |
String |
The student's name |
gradeLevel |
int |
The student's grade level |
gpa |
double |
The student's GPA |
Instance variables are declared inside the class, but outside all methods and constructors.
public class Dog
{
private String name;
private int age;
public Dog(String dogName, int dogAge)
{
name = dogName;
age = dogAge;
}
}
The variables name and age are instance variables.
They are declared at the top level of the class.
| Feature | Instance Variable | Local Variable |
|---|---|---|
| Where declared? | Inside class, outside methods | Inside a method or constructor |
| Belongs to? | Object | Method or block |
| How long does it last? | As long as the object exists | Only while the method or block runs |
| Default value? | Yes | No |
| Usually private? | Yes | Not usually |
public class GamePlayer
{
private String username; // instance variable
private int score; // instance variable
public void addPoints(int points)
{
int bonus = 5; // local variable
score = score + points + bonus;
}
}
username and score belong to the object.
points and bonus only exist inside the method.
Instance variables automatically receive default values if they are not assigned.
| Data Type | Default Value |
|---|---|
int |
0 |
double |
0.0 |
boolean |
false |
char |
'\u0000' |
Object references like String |
null |
public class Player
{
private int score;
private boolean active;
private String name;
}
If no constructor assigns values:
score // 0
active // false
name // null
Instance variables are usually marked private.
private int score;
This protects the data from being changed directly by outside classes. This idea is called encapsulation.
public int getScore()
{
return score;
}
public void addPoints(int points)
{
if (points > 0)
{
score += points;
}
}
A constructor often gives starting values to instance variables.
public class BankAccount
{
private String owner;
private double balance;
public BankAccount(String accountOwner, double startingBalance)
{
owner = accountOwner;
balance = startingBalance;
}
}
When an object is created:
BankAccount acct = new BankAccount("Maria", 100.00);
The object stores:
owner = "Maria"
balance = 100.00
Methods inside the class can read and modify instance variables.
public class Counter
{
private int count;
public Counter()
{
count = 0;
}
public void increase()
{
count++;
}
public int getCount()
{
return count;
}
}
Example use:
Counter c = new Counter();
c.increase();
c.increase();
System.out.println(c.getCount());
Output:
2
The object remembers the value of count.
public class Player
{
private String name;
private int score;
public Player(String playerName)
{
name = playerName;
score = 0;
}
public void addPoints(int points)
{
score += points;
}
public String getName()
{
return name;
}
public int getScore()
{
return score;
}
}
Example:
Player p1 = new Player("Alex");
Player p2 = new Player("Jordan");
p1.addPoints(10);
p2.addPoints(25);
System.out.println(p1.getName() + ": " + p1.getScore());
System.out.println(p2.getName() + ": " + p2.getScore());
Output:
Alex: 10
Jordan: 25
Even though both objects come from the same class, each object has its own
name and score.
this With Instance VariablesSometimes a parameter has the same name as an instance variable.
public class Student
{
private String name;
public Student(String name)
{
this.name = name;
}
}
this.name means the instance variable.
name by itself means the parameter.
public class Rectangle
{
private int width;
private int height;
public Rectangle(int width, int height)
{
this.width = width;
this.height = height;
}
}
this refers to the current object.
public class Book
{
private String title;
private String author;
private int pages;
public Book(String bookTitle, String bookAuthor, int numberOfPages)
{
title = bookTitle;
author = bookAuthor;
pages = numberOfPages;
}
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public int getPages()
{
return pages;
}
public void addPages(int extraPages)
{
if (extraPages > 0)
{
pages += extraPages;
}
}
}
Example use:
Book b = new Book("The Hobbit", "J.R.R. Tolkien", 310);
System.out.println(b.getTitle());
System.out.println(b.getAuthor());
System.out.println(b.getPages());
b.addPages(5);
System.out.println(b.getPages());
Output:
The Hobbit
J.R.R. Tolkien
310
315
Incorrect:
public class Student
{
public Student(String studentName)
{
String name = studentName;
}
}
name is a local variable.
It disappears after the constructor finishes.
Correct:
public class Student
{
private String name;
public Student(String studentName)
{
name = studentName;
}
}
privateNot recommended:
public int score;
Better:
private int score;
Student s1 = new Student("Ava");
Student s2 = new Student("Noah");
Student is the class.
s1 and s2 are objects.
public void addOne()
{
count++;
}
If count is an instance variable, it remembers its value after the method ends.
On the AP Computer Science A exam, instance variables are important because they appear in many classes and FRQs.
You may be asked to:
public class ScoreCard
{
private String playerName;
private int score;
public ScoreCard(String name)
{
playerName = name;
score = 0;
}
public void addScore(int points)
{
if (points > 0)
{
score += points;
}
}
public int getScore()
{
return score;
}
}
| Term | Meaning |
|---|---|
| Class | A blueprint for creating objects |
| Object | An instance of a class |
| Instance Variable | A variable that belongs to an object |
| Field | Another name for an instance variable |
| Constructor | A special method used to create and initialize an object |
| Encapsulation | Protecting data by making fields private |
| Getter | A method that returns the value of a field |
| Setter | A method that changes the value of a field |
this |
Refers to the current object |
private
this.name refer to?name in the current object.
Create a class called VideoGamePlayer.
Your class should have these instance variables:
private String username;
private int level;
private int health;
Your class should include this constructor:
public VideoGamePlayer(String name)
This constructor should set:
username = name;
level = 1;
health = 100;
Add these methods:
public void levelUp()
public void takeDamage(int amount)
public String getUsername()
public int getLevel()
public int getHealth()
Instance variables are the data stored inside an object.
They allow an object to remember information between method calls.
A good Java class usually has:
private instance variables
a constructor
methods that use or change the variables
getter methods when outside classes need information