Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175
Classes and Objects | Building Blocks Java

Classes and Objects

The primary distinguishing feature of OOP languages is the class. A class is a data structure that can associate the methods which act on an object with the object itself. In pre-OOP languages methods and data were separate. In OOP languages they are all part of classes.

Programming languages provide a number of simple data types like int, float and String. However very often the data you want to work with may not be simple ints, floats or Strings. Classes let programmers define their own more complicated data types.

For instance let’s suppose your program needs to keep a database of web sites. For each site you have a name, a URL, and a description. In traditional programming languages you’d have three different String variables for each web site. With a class you combine these into one package like so:

class website {

String name;
String url;
String description;


These variables (name, url and description) are called the members of the class. They tell you what a class is and what its properties are. They are the nouns of the class.

In our web site database we will have many thousands of websites. Each specific web site is an object. The definition of a web site though, which we gave above, is a class. This is a very important distinction. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class.

To instantiate an object in Java we use the new operator. Here’s how we’d create a new web site:

website x = new website();

Once we’ve got a website we want to know something about it. To get at the member variables of the website we can use the . operator. Website has three member variables, name, url and description, so x has three member variables as well, x.name, x.url and x.description. We can use these just like we’d use any other String variables. For instance:

website x = new website();

x.name = “Cafe Au Lait”;
x.url = “http://metalab.unc.edu/javafaq/”;
x.description = “Really cool!”;

System.out.println(x.name + ” at ” + x.url + ” is ” + x.description);

Comments are closed.