JAVA and OOPs Concepts

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods)

Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as model and color, and methods, such as drive and brake.

A Class is like an object constructor, or a “blueprint” for creating objects.

What is a Class?

A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of a certain kind.

Create a Java Class

To create a class, use the keyword class:

Create a class named “Car” with a variable model and colour:

public class Car{
  string model;
  string colour;
}

What is an Object?

An object is a representative or specimen of a class. Software objects are often used to model real-world objects you find in everyday life.

Create a JAVA Object

In Java, an object is created from a class. We have already created the class named Car, so now we can use this to create objects.

To create an object of Car, specify the class name, followed by the object name, and use the keyword new:

Car myCar = new Car();

Examples of class and objects

ClassObjects
Fruit Apple
Banana
Mango
Car Volvo
Audi
Toyota
Examples – Class and Objects


Features of OOPs :

Abstraction 

Abstraction is the process of exposing the relevant things and hiding the irrelevant details. The easiest way to understand and appreciate this concept of handling complexity is by studying the example of Globe, a model/prototype of earth that is used by students to understand its geography. Globe provides only that information that is required and if too much of information is mentioned in it i.e. streets, lakes etc, it becomes too complex to comprehend. Hence Globe abstracts unwanted information and makes it easy to comprehend the complex earth.

JAVA Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal {
  public abstract void animalSound();
  public void sleep() {
    System.out.println("Zzz");
  }
}
 
 

From the example above, it is not possible to create an object of the Animal class:

Animal myObj = new Animal(); // will generate an error

To access the abstract class, it must be inherited from another class. Let’s convert the Animal class we used in the Polymorphism chapter to an abstract class:

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.

Example

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Encapsulation 

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The data is not accessible to the outside world and only those functions that are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. The insulation of the data from the direct access by the program is called data hiding.
In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (Object is a capsule encapsulating data and behavior). All communication to it is through messages (function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface. Therefore, we need not know anything about what is in the object when we use it.

JAVA Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

Example

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}
 
 

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

Example

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.name = "John";  // error
    System.out.println(myObj.name); // error 
  }
}

Inheritance 

Inheritance is the process by which one class acquires the properties and functionalities of another class. This is important because it supports the concept of hierarchical classification.. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.

Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group the “inheritance concept” into two categories:

  • subclass (child) – the class that inherits from another class
  • superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Example

class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
 

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was set to private, the Car class would not be able to access it.

Why And When To Use “Inheritance”?

– It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks.


The final Keyword

If you don’t want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}

The output will be something like this:Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
                  ^
1 error)

Polymorphism 

Polymorphism is a feature that allows one interface to be used for a general class of actions. An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.
Ex:
add(int a, int b)
add(int a, float b, int c)
add(int a, int b, float c, double d)
Here different datatypes are being added using the same interface.

Java Polymorphism

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds – And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Example

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.

Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Example

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

Setting up Java Development Environment – Windows

Setting up Java Development Environment – Windows

Step 1 : Go to URL : http://java.oracle.com and Click on Java SE link under Download section


Step 2: Click on JDK download icon for example Java Platform ( JDK ) 7u51  installer

Step 3 : Accept the licence Agreement and download the correct installer  depending upon operating system i.e. Linux , MAC OS , Solaris and Windows and on 64 or 86 bit . Click on Download link and download the installer. For example for Windows 64 bit operating system : jdk-7u51-windows-x64.exe

Step 4 : Click on downloaded installer and install JDK
Step 5 : Navigate to Program files and locate bin folder under Java folder. Note down the path of bin folder : C:Program FilesJavajdk1.7.0_51bin

Step 6 :  Go to Control Panel -> System -> Environment Variables

Step 7 : Edit Path Environment Variables by adding collon and path of Java bin folder

Eclipse Download & Setup

Eclipse Download & Setup

1. Eclipse can be downloaded from blow site  : http://www.eclipse.org/

www.eclipse.org
http://www.eclipse.org

2. Click on Download link of Eclipse Home page

Eclipse Downloads

3. Click on Eclipse IDE for Java Developers – Windows 32 Bit link on Eclipse Downloads page.

4. Click on Download icon on Eclipse downloads – mirror selection page and zipped file called eclipse-java-indigo-SR1-win32.zip is downloaded
5. Extract the zip files . Below are contents of eclipse-java-indigo-SR1-win32.zip file :

eclipse-java-indigo-SR1-win32
eclipse-java-indigo-SR1-win32

6. Create a new folder called “Eclipse” under Program Files and copy contents of zipped file

Java 5

New Features in Java 5

  1. Generics – Provides compile-time type safety while still allowing a type or method to operate on objects of various types.
  2. Enhanced for Loop – The for statement can now be used to iterate over an array and a collection.
  3. Autoboxing/unboxing –  Automatic conversion of primitives to wrapper types and vice versa.
  4. Enum type – A new enumeration type in Java.
  5. Varargs – Allows a method to accept a variable number of arguments.
  6. Static import – Eliminates the need to qualify static members with class names.
  7. Annotations – A special type of interface used for annotating any program elements.

 
Downloading and Installing Java 5

 

Before you can start compiling and running Java programs, you need to download and install the JDK as well as configure some system environment variables. It is also recommended that you download the API documentation.

 

Downloading and Installing the JDK

 

The JDKs for Windows, Linux, and UNIX can be downloaded from this URL:

 

Once you click the link, you’ll be redirected to a page that lets you select an installation for your platform: Windows, Linux, or Unix. The 64 bit versions for certain platforms are available. Also, note that the same link also provides the JRE. However, you need the JDK, and the JDK includes the JRE.

 

For Macintosh, download the JDK from this URL:

 

After obtaining the JDK, you need to install it. Installation varies from one operating system to another.

 

Setting the Path Environment Variable on Windows

 

To set the PATH environment variable on Windows NT, Windows 2000, and Windows XP, do these steps:

 

1. Click Start, Settings, Control Panel.

2. Double-click System. on Windows NT, select the Environment tab. On Windows 2000 and Windows XP select the Advanced tab and then click on Environment Variables.

3.Locate the Path environment variable in the User Variables or System Variables panes.The value of Path is a series of directories separated by semicolons. Now, add the full path to the bin directory of your Java installation directory to the end of the existing value of Path.The directory looks something like:C:Program FilesJavajdk1.5.0_bin

 4.Click Set, OK, or Apply.

 

Java 2, J2SE, J2EE, J2ME

There were three editions of Java 2:

 
  1. Java 2 Platform, Standard Edition (J2SE) – J2SE is basically the JDK. It also serves as the foundation for technologies defined in J2EE.
  2. Java 2 Platform, Enterprise Edition (J2EE) – It defines the standard for developing component-based multi-tier enterprise applications. Features include Web services support and development tools (SDK).
  3. Java 2 Platform, Micro Edition (J2ME) – It provides an environment for applications that run on consumer devices, such as mobile phones, personal digital assistants (PDAs), and TV set-top boxes. J2ME includes a JVM and a limited set of class libraries.

Javac , JVM , JRE , JDK

  • Javac , JVM , JRE , JDK

  • Javac  is Java compiler. This compiles Java code to byte code

  • JVM stands for Java Virtual Machine. This is a native application which runs byte code.

  • JRE stands for Java Runtime Environment. JRE contains both a JVM and class libraries. This is used to run byte code

  • JDK stands for Java Development Kit. JDK includes the JRE plus a compiler and other tools. This is required software to write and compile Java programs.

Java – Introduction

Java – Introduction

Java is a Object Oriented Programming language. Java was introduced in 1995 by Sun Microsystems .
Java is platform indepedent i.e Java Program can run on multiple operating systems .
Java can be converted to machince code. Machince code can run on JVM i.e Java Virtual Machine.
A JVM is a native application that interprets machine code. JVM is available in many platforms i,e Windows , UNIX , LINUX etc hence Java is platform independent language