Objects and Classes

 
Readings were:
and chapter 1 of Guzdial & Ericson book

 

 

Objects

 

 

Objects are everywhere - like a bicycle, a dog, a crab, etc.

Objects have 2 things (as far as we are concerned): state and behavior.

Objects have state (in Java, called fields. Others also use terms like variables).

Examples: height, weight, speed, number of legs, etc.

 

Objects have behavior (in Java, called methods. Others also use terms like functions or event handlers) – they do things and can react to things (in programming parlance, they can read or alter the states).

Examples: person.walk(), dog.bark(), cat.meow()

Notice the parentheses at the end. That tells you that you are calling a method.

 

See this visual diagram of a bicycle object (with methods and state) from java tutorial.

A lot of people use this kind of visual representation to explain objects to new programmers.

It looks sort of like an orange or some other kind of fruit, with the methods on the outer part of the body, and the different kinds of state in the middle, like seeds.

 

Methods often are responsible for reading or changing (writing) to the state (or fields). For example, the bicycle has a state called “speed” and a behavior (method) called “applyBrake()”. If you call the applyBrake method, the value of the speed state will lower.

 

Methods also can make sure you don't get into invalid states. For example a changeGear(int n) method might only accept numeric values between 1 and 6. If you tried to pass a text value (like “six”), your java code would not even compile. If you tried to pass a numeric value that is out of range (like 0), you as the programmer can control how the method handles it. Ignore it and silently do nothing? Pick the closest valid gear (1)? Or, and this is most common, throw what is called an exception, an error that stops the program if not correctly handled. We'll explain exceptions more later.

 

In Java, everything is an object. Java is an object-oriented programming language (OOPL).

 

Classes

 

 

A class is a type of object. You can have a dog class, a vehicle class. Classes are related to each other hierarchically, like a biology species tree or a family tree. A bicycle class is a subclass of the vehicle class, for example, as is a car class or a boat class. Say that the vehicle class has 2 numeric fields: speed and numberOfWheels. All vehicles have a speed, but different kinds of vehicles have different numbers of wheels, or none in the case of a typical boat. Some subclasses may add new fields or states. For example, a class called MotorizedVehicle may add fields like horsePower and fuelType (gas, electric, steam, ...).

 

But in the Java class hierarchy ultimately every class is a subclass of the special Object class. So for example a Car class might have a hierarchy like so:

 

Object Vehicle MotorizedVehicle Car

 

You can tell a class's superclass (or parent class) by looking at the class declaration in the java code:

 

class MotorizedVehicle extends Vehicle {

...



class Car extends MotorizedVehicle {

...



class Vehicle {

...

 

If there is no “extends ...” part, then it is assumed that “Object” is the superclass.

 

In Java, a class can only have one parent superclass (single inheritance). Other languages (like Python, C++) do allow multiple parents (multiple inheritance), or else allow “injecting” more than one class into a class (like Scala's “traits” and other languages' “mixins”).

Java does have a way to combine the behavior of multiple classes, however, called interfaces, which we'll discuss later.

 

The relationship between classes and objects

 

Another way to think of classes in java is to imagine a class as a factory producer of objects. And in fact advanced programmers do use the term “factory” to denote this programming pattern.

 

A java object (not to be confused with the Object class) is an instance of a class. You can think of it for example as a particular bike being produced by the Bike factory.

 

 

To create an instance object of a class, you can use code like so:

Car c; //declaring a variable or field called “c” 
       //that has a class type of “Car”

c = new Car(); //initialize a new Car object instance, 
               //and store a reference to it in the variable c

 

or in one line:
Car c = new Car();

 

The first line declares a variable or field with the class type of Car. The name of that variable or field is “c”. Then, using the equal sign (=), you assign something to that variable c. What you are saying in this case, is “create a new Car object instance, and store it in the variable c.”

Now you can refer to that car instance by using the name of the stored variable (“c”).

You can call methods on that instance and read state:

    c.applyBrake(); //call the applyBrake method of the car

    System.out.println(c.speed); //print the car's speed out to the console

 

Side Note on Code Comments

 

Anytime the java compiler is reading a line of java code and comes across two forward slashes (//), it ignores everything on the rest of that line. That is called a comment. It lets a programmer insert notes for him or herself or other programmers to help explain or understand what the code is doing.

 

You can also have comments that span multiple lines. You start the comment with /*

and end it with */

This is also useful to comment out a section of code that for example may not be finished yet or may be the source of problems.

There is a 3rd kind of special comment called a documentation comment, or javadoc.

It starts with /** and ends with */ and is placed above a class declaration or a method declaration. These comments are used to generate official documentation about a class and its methods.

See some examples in Greenfoot by double clicking the Actor class and viewing its java source code and documentation. Notice also on the top right of the window that you can switch between the documentation viewer and the source code editor.

 

Example of a class

 

 

The body of a class

 

class Bicycle {

    //The class body is everything from the above left curly brace to the last right curly brace

    //below is a field or member variable that only internal methods can access

    private int speed; 




    //This is a special method called a constructor.

    //It is called when you instantiate an object instance: b = new Bicyle(20);

     public Bicycle(int startSpeed) {

         speed = startSpeed; //this sets the “speed” field to the value passed to the method

     }




    //a method called applyBrake that subtracts a numeric value from the “speed” variable

    public void applyBrake(int decrement) {

       speed -= decrement;  // “-=” is a shortcut for: speed = speed – decrement;

    }

}

 

 

Declaring fields and methods in a class

Fields (also known as member variables) and methods in a class:

 

Public vs. private fields & methods

You can make it so only methods internal to a class have access to a field (private), or internal methods of the class plus any subclasses (protected), or make them accessible from outside the class (public).

 

You can also have public/private/protected methods.

 

See the 'access modifiers' section of above url, and for a more complete listing:

 

Naming conventions:

 

Variable names:
-case-sensitive

-start with a letter (upper or lower, but usually lower)

-usually are all lower case (like “speed”)

 

Method names:

-also case-sensitive and start with a letter

-in Java, they usually start with a lower case letter but are camelCased

(like “applyBrake”)

 

Class names:

-also case-sensitive and start with a letter

-start with an upper case letter (like “Car”)

 

Example of a method, and how to name a method

 

Overloading Methods

 

The above URL also explains Overloading Methods, or how and why you might have multiple methods in a class that all have the same name, but accept a different number or kind of parameters.

 

You can also have multiple constructors. For example:

 

Passing parameters to a method or constructor

 

Referencing class fields of an object, and calling methods of an object:

 

Referencing a field from within an object using “this” (or an implicit “this”):

 

The body of a method

Methods do things, but they can also return values back to you. To do that, you use a “return” statement in your method body:

 

Static (shared) vs. Instance Fields and Methods

 

Remember that one way to think of a class is as a factory of object instances.

Well you can have some state (fields) that is copied over to each instance (like speed of a particular bike), and some state that is shared between all instances (kept at the factory) and doesn't usually change (static), or else if the static shared variable does change, it changes for ALL bike instances. For example: numberOfWheels. All bikes have 2 wheels. There is no reason to copy that value to each instance of a bike.

A more practical example of a static field for a Bicycle class might be numberofbikes. You can think of it as the factory keeping track of how many bikes have been created. And sometimes in programming for example, you might want to keep track of that, or even limit the amount of instances that can be created. For example to save memory.

 

You can also have static (or shared) methods, that can read or write (only) static fields. For example “getTotalBikes()” could return the number of bikes instantiated.

 

Remember one thing: Static = shared. Static = shared. Static = shared.

Static variables are shared between all instances. Actually Visual Basic (designed more with beginners in mind) uses the keyword Shared instead of static.

 

Initializing values for a field (static or instance)

 

Summary of classes, objects, fields, & methods

 

 

 

Inheritance & Interfaces

 

The short version:

 

The long version:

 

Interfaces

Defining an interface

Example use of an interface

Using an interface type instead of a class type

 

Inheriting an interface (like interface subclasses and superclasses)

 

Further reading on interfaces

 

Inheritance

 

Examples of inheritance, and casting

 

Overriding methods: (a subclass changes the behavior of a superclass' method)

 

“this” vs. “super” keywords

 

Abstract classes and abstract methods

(vs. interfaces and interface methods)

An abstract class cannot be instantiated. Think of it as an incomplete class. It fills in some default behavior (methods), but the rest needs to be filled in by a subclass. An example of this in Greenfoot is the Actor class. Double click the Actor class to see its code.

 

Difference between interfaces and abstract classes

An interface is sort of like a completely abstract class. There are no fields (no state), no method bodies. Only the name of the interface is specified, and the names and parameters and return values of the methods.

 

Abstract Classes vs. Interfaces

See:

http://www.javapassion.com/javase/javainterface.pdf

 

Why?

In Java, you can only have 1 superclass (using the extends keyword). That includes abstract classes.

However, a class can implement as many interfaces as it wants (using the implements keyword). Hence, interfaces almost allow to have multiple inheritance, but in a safer and less confusing way. You don't have to worry about 2 superclasses that might have conflicting method names or state.

 

 

Groups:

Disclaimer

Any opinions expressed here, except as specifically noted, are those of the individual authors or commenters and do not necessarily represent the views or policies of the Department of Instructional Technology and Learning Sciences, the Emma Eccles Jones College of Education and Human Services, or Utah State University.