Problem 163.1
Web Addresses
Classes are an easy way to create a single variable that can hold several different values. For example, consider the problem of storing a mailing address. The address has many parts, but is conceptually one unit.
Files Needed: WebAddresses.java
The code provided will create a class called “Address” that contains four fields:
a field for the house number / street name (a String) a field for the city name (a String) a field for the state (a String) a field for the zip code (an int)
The example code creates an instance of the Address class and assigns it to a variable of type Address
.
What You Should See
1313 Disneyland Dr, Anaheim, California 92802
What You Should Do on Your Own
Assignments turned in without these things will receive half credit or less.
- The code provided only creates one Address object. Change the code to create and print out two more Address objects.
Clarifications
Class
A class is a general template or prototype for an object. Classes define the general attributes and behaviours for any objects we may need in our program.
If we think about a human class, in general, every human has:
- a name
- a birthdate
- weight
- height
Humans obviously have other attributes but, those will do for now.
class Human {
String name;
Date birthdate;
double weight;
double height;
}
Object
An object is a specific instance of a class. You are a specific instance of the human
class.
Every object has specific data stored in it.
We can create a new object by using the familiar new
keyword in Java.
Human someHuman = new Human();
We can the assign specific values to each of the object’s attributes.
someHuman.name = "Mr. Gallo";
someHuman.weight = 72.5;
someHuman.height = 172;
We can access these attributes the same way we set them.
System.out.println("This human is " + someHuman.height + "cm tall.");
It is like using Arrays, except rather than using []
to reference a particular piece of data,
we use “dot notation” and use a descriptive name for the data being referenced. This makes our code much easier to read.
◄ 153: Hangman 163.2: Web Addresses Scanner ►
Adapted from ProgrammingByDoing.com
©2013 Graham Mitchell
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.