Object Oriented

Object-Oriented Programming Concepts

If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.

What Is an Object?

An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans etc. All these objects have a state and behavior.
If we consider a dog then its state is - name, breed, color, and the behavior is - barking, wagging, running
If you compare the software object with a real world object, they have very similar characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods.
So in software development methods operate on the internal state of an object and the object-to-object communication is done via methods.

What Is a Class?

A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

Classes in Java:

A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class Dog{
   String breed;
   int age;
   String color;

   void barking(){
   void hungry(){
   void sleeping(){
A class can contain any of the following variable types.
  • Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kind of methods. In the above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.

What Is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.
public class Animal{

public class Mammal extends Animal{

public class Reptile extends Animal{

public class Dog extends Mammal{
Now based on the above example, In Object Oriented terms following are true:
  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are sub classes of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.


public class Dog extends Mammal{

   public static void main(String args[]){

      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
This would produce following result:

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.


public interface Animal {}

public class Mammal implements Animal{

public class Dog extends Mammal{

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal
interface Animal{} class Mammal implements Animal{} public class Dog extends Mammal{ public static void main(String args[]){ Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } This would produce following result:
true true true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
 private Speed sp;
This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.
In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. SO basically what happens is the users would ask the Van class to do a certain action and the Vann class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{} 
However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance

What Is an Interface?

An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it.

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
An interface is similar to a class in the following ways:
  • An interface can contain any number of methods.
  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
  • The bytecode of an interface appears in a .class file.
  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.
However, an interface is different from a class in several ways, including:
  • You cannot instantiate an interface.
  • An interface does not contain any constructors.
  • All of the methods in an interface are abstract.
  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  • An interface is not extended by a class; it is implemented by a class.
  • An interface can extend multiple interfaces.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:


Let us look at an example that depicts encapsulation:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements

public interface NameOfInterface
   //Any number of final, static fields
   //Any number of abstract method declarations\
Interfaces have the following properties:
  • An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.
  • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
  • Methods in an interface are implicitly public.


/* File name : Animal.java */
interface Animal {

   public void eat();
   public void travel();

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");

   public void travel(){
      System.out.println("Mammal travels");

   public int noOfLegs(){
      return 0;

   public static void main(String args[]){
      MammalInt m = new MammalInt();
This would produce following result:
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:
  • Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
  • The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
  • An implementation class itself can be abstract and if so interface methods need not be implemented.
When implementation interfaces there are several rules:
  • A class can implement more than one interface at a time.
  • A class can extend only one class, but implement many interface.
  • An interface can extend another interface, similarly to the way that a class can extend another class.

Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);

//Filename: Football.java
public interface Football extends Sports
   public void homeTeamScored(int points);
   public void visitingTeamScored(int points);
   public void endOfQuarter(int quarter);

//Filename: Hockey.java
public interface Hockey extends Sports
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

Tagging Interfaces:

The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as:
package java.util;
public interface EventListener
An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class: This situation is where the term tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.

What Is a Package?

A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform.

Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
  • java.lang - bundles the fundamental classes
  • java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.

Creating a package:

When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.


Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;

interface Animal {
   public void eat();
   public void travel();
Now put an implementation in the same package animals:
package animals;

/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");

   public void travel(){
      System.out.println("Mammal travels");

   public int noOfLegs(){
      return 0;

   public static void main(String args[]){
      MammalInt m = new MammalInt();
Now you compile these two files and put them in a sub-directory called animals and try to run as follows:
$ mkdir animals
$ cp Animal.class  MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

The import Keyword:

If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.


Here a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.
package payroll;

public class Boss
   public void payEmployee(Employee e)
What happens if Boss is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.
  • The fully qualified name of the class can be used. For example:
  • The package can be imported using the import keyword and the wild card (*). For example:
import payroll.*;
  • The class itself can be imported using the import keyword. For example:
import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.

The Directory Structure of Packages:

Two major results occur when a class is placed in a package:
  • The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
  • The name of the package must match the directory structure where the corresponding bytecode resides.
Here is simple way of managing your files in java:
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example:
// File Name :  Car.java

package vehicle;

public class Car {
   // Class implementation.   
Now put the source file in a directory whose name reflects the name of the package to which the class belongs:
Now the qualified class name and pathname would be as below:
  • Class name -> vehicle.Car
  • Path name -> vehicle\Car.java (in windows)
In general a company uses its reversed Internet domain name for its package names. Example: A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this:
At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class
For example:
// File Name: Dell.java

package com.apple.computers;
public class Dell{
class Ups{
Now compile this file as follows using -d option:
$javac -d . Dell.java
This would put compiled files as follows:
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:

By doing this, it is possible to give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\comptuers.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable:

To display the current CLASSPATH variable, use the following commands in Windows and Unix (Bourne shell):
  • In Windows -> C:\> set CLASSPATH
  • In Unix -> % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use :
  • In Windows -> C:\> set CLASSPATH=
  • In Unix -> % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable:
  • In Windows -> set CLASSPATH=C:\users\jack\java\classes
  • In Unix -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

No comments:

Post a Comment