Navigation

Object Oriented Programming Concepts

Object – Oriented Programming Concepts

1) What is an Object?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current speed) and behavior (changing gear, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.

A software object.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

A picture of an object, with bibycle methods and instance variables.

A bicycle modeled as a software object.

2) What is a Class?

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:

                class Bicycle {

                    int speed = 0;
                    int gear = 1;

                    void speedUp(int increment) {
                        speed = speed + increment;
                    }

                    void applyBrakes(int decrement) {
                        speed = speed - decrement;
                    }

                    void printStates() {
                        System.out.println(" speed:" + speed + " gear:" + gear);
                    }
                }
            

The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The field’s speed, and gear represent the object's state, and the methods (changeGear, speedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:

                class BicycleDemo {
                    public static void main(String[] args) {

                        // Create two different
                        // Bicycle objects
                        Bicycle bike1 = new Bicycle();
                        Bicycle bike2 = new Bicycle();

                        // Invoke methods on
                        // those objects
                        bike1.speedUp(10);
                        bike1.changeGear(2);
                        bike1.printStates();

                        bike2.speedUp(10);
                        bike2.changeGear(2);
                        bike2.speedUp(10);
                        bike2.changeGear(3);
                        bike2.printStates();
                    }
                }
            

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

speed:10 gear:2

speed:20 gear:3

3) What is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, andTandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A diagram of classes in a hierarchy.

A hierarchy of bicycle classes.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

                class MountainBike extends Bicycle {

                    // new fields and methods defining 
                    // a mountain bike would go here

                }
            

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

4) What is an Interface?

As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:

                interface Bicycle {

                    void changeGear(int newValue);

                    void speedUp(int increment);

                    void applyBrakes(int decrement);
                }
            

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:

                class ACMEBicycle implements Bicycle {

                    int speed = 0;
                    int gear = 1;

                   // The compiler will now require that methods
                   // changeGear, speedUp, and applyBrakes
                   // all be implemented. Compilation will fail if those
                   // methods are missing from this class.

                    void changeGear(int newValue) {
                         gear = newValue;
                    }

                    void speedUp(int increment) {
                         speed = speed + increment;   
                    }

                    void applyBrakes(int decrement) {
                         speed = speed - decrement;
                    }

                    void printStates() {
                         System.out.println("cadence:" +
                             cadence + " speed:" + 
                             speed + " gear:" + gear);
                    }
                }
            

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

5) What Is a Package?

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.


Introduction to Java

Introduction to Java

1) History

Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.

Sun Microsystems was acquired by the Oracle Corporation in 2010.

2) Java Platform Overview

Java technology is used to develop applications for a wide range of environments. In this section, get a high-level view of the Java platform and its components.

Java Language

Java is an object-oriented programming language.

Java is a Platform Independent i.e. Java source code files are compiled into a format called bytecode which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems.

Java Compiler

When you program for the Java platform, you write source code in .java files and then compile them. The compiler checks your code against the language's syntax rules, then writes out bytecodes in .class files. Bytecodes are standard instructions targeted to run on a Java virtual machine (JVM).

JVM

At run time, the JVM reads and interprets .class files and executes the program's instructions on the native hardware platform for which the JVM was written. The JVM interprets the bytecodes just as a CPU would interpret assembly-language instructions. The difference is that the JVM is a piece of software written specifically for a particular platform. The JVM is the heart of the Java language's "write-once, run-anywhere" principle. Your code can run on any chipset for which a suitable JVM implementation is available. JVMs are available for major platforms like Linux and Windows, and subsets of the Java language have been implemented in JVMs for mobile phones and hobbyist chips.

Garbage Collector

Rather than forcing you to keep up with memory allocation (or use a third-party library to do this), the Java platform provides memory management out of the box. When your Java application creates an object instance at run time, the JVM automatically allocates memory space for that object from the heap, which is a pool of memory set aside for your program to use. The Java garbage collector runs in the background, keeping track of which objects the application no longer needs and reclaiming memory from them. This approach to memory handling is called implicit memory management because it doesn't require you to write any memory-handling code. Garbage collection is one of the essential features of Java platform performance.

Java Development Kit

When you download a Java Development Kit (JDK), you get in addition to the compiler and other tools a complete class library of prebuilt utilities that help you accomplish just about any task common to application development.

Java Runtime Environment

The Java Runtime Environment (JRE; also known as the Java runtime) includes the JVM, code libraries, and components that are necessary for running programs written in the Java language. It is available for multiple platforms.

3) Setting up Java Development Environment

In this section, you'll get instructions for downloading and installing JDK 6 and the current release of the Eclipse IDE, and for setting up your Eclipse development environment.

Installing JDK

Follow these steps to download and install JDK 6.

  1. Download Java Platform (JDK) from Java SE Downloads.

  2. When the download is complete, run the install program. And install JDK in your hard drive.

You now have a Java environment on your machine. Next, you will install the Eclipse IDE.

Install Eclipse

To download and install Eclipse, follow these steps:

  1. Browse to Eclipse Download Directory.

  2. Download Eclipse IDE for Java Developers.

  3. Extract the contents of the .zip file to a location on your hard drive that you'll be able to remember easily.

Setting up Eclipse

The Eclipse IDE sits atop the JDK as a useful abstraction, but it still needs to access the JDK and its various tools. Before you can use Eclipse to write Java code, you have to tell it where the JDK is located.

To set up your Eclipse development environment:

  1. Launch Eclipse by double-clicking on eclipse.exe (or the equivalent executable for your platform).

  2. The Workspace Launcher will appear, allowing you to select a root folder for your Eclipse projects. Choose a folder you will easily remember, such as C:\home\workspace on Windows or ~/workspace on Linux.

  3. Dismiss the Welcome to Eclipse screen.

  4. Click Window > Preferences > Java > Installed JREs. Below figure shows the setup screen for the JRE:

    Configuring the JDK used by Eclipse
  5. Eclipse will point to an installed JRE. You need to make sure you use the one you downloaded with JDK 6. If Eclipse does not automatically detect the JDK you installed, click Add... and in the next dialog Standard VM, then click Next.

  6. Specify the JDK's home directory (such as C:\home\jdk1.6.0_20 on Windows), then click Finish.

  7. Confirm that the JDK you want to use is selected and click OK.

Eclipse is now set up and ready for you to create projects and compile and run Java code. The next section will familiarize you with Eclipse.


Java Tutorial Home

Vasanth Blog Home

Vasanth Blog