Quick Index
Overview


Data
We want to code a Person type (class) with data properties.

Later, we'll construct Person objects with data values.

Here we show five different objects.


Problem Statement


Code the data properties into the "Person" class. Assume Person has one property named "firstName" of data type String.

Note: We'll use "class" interchangeably with "object type" in this example.
Person
😊
firstName

Previous Work



Plan


Person Data
We previously determined that a Person type has one property which is "firstName".

This is a very simple model of a person (for this example)
Object Type: Person

Properties:
	firstName -- first name of person
Previous Code
We recently coded an empty class body for the Person class. This is our baseline (starting point).
public class Person {

}
New Code
We now need to add the data (object properties)
public class Person {

	//Add object properties here

}


Sketch / Doodle


Before starting on a problem it is helpful to step away from the computer and walk over to a white board or scratch paper.

Draw a quick sketch of what you are going to code. This habit is especially helpful as you go forward.

Here we have done a very quick doodle of what we are coding. We have a person class with one ivar as noted.
Person
	-> ivar "firstName" of type "String"

Coding An Ivar


We need to add a property to our class. In Java we call these properties instance variables (abbreviated as "ivars") .

For this problem we have one instance variable called "firstName".

Code
This is how to code the ivar into the Person class.
public class Person {

	private String firstName;

}


Saving Person Class




lanation

Let's look at the coding details.

Statement Decomposed
  • "private" -- indicates this ivar is private and not accessible to other objects
  • String -- indicates the type for this specific ivar
  • "firstName" -- is the name we are giving the ivar
public class Person {

	
1
private
2
String firstName; }

Notes


When we write code we are effectively talking to the Java compiler, e.g. "Hello compiler, this ivar is private, it's a String type, it's name is firstName"

More Data Types


In this example our ivar had a "String" data type. Find more information on different types we can use here....

Naming Instance Variables


See this topic... for guidelines for naming ivars.

Multiple Instance Variables


Here is the example we followed. We defined one ivar.
public class Person {

	private String firstName;

}
Here is an example with multiple ivars.

Don't forget the semi-colon terminator at the end of each statement/line
public class Dog {

	private String name;
	private int weight;
	private String favoriteFood;

}
Here is another example with multiple ivars.
public class Point {

	private int x;
	private int y;

}