CORE JAVA: OOPs (Object Oriented Programming System)

Introduction

 

Object means a real world entity such as a pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.It simplifies the software development and maintenance by providing some concepts:

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Java class

A collection of objects is called class. It is a logical entity. Defines a new data type.

Once defined, this new data type can be used to create objects of that type.

A class is a template for an object.

A class in Java can contain:

  • fields
  • methods
  • constructors
  • blocks
  • nested class and interface

Defining a Class:


Defined by specifying the data that it contains and the code that operates on that data.

class.png

  • Data or variables, defined within a class are called instance variables or fields.
    A code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

EXAMPLE:

1)


ex.png

2)


box.png

output2:

o

 

 

Java Object

  • An object is an instance of a class.
  • An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.
  • It can be physical or logical (tangible and intangible).
  • The example of an intangible object is banking system.
  • For Example, Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Declaring Objects:


Obtaining objects of a class is a two-step process:

  • Declare a variable of the class type –a reference to an object.
  • Acquire an actual, physical copy of the object and assign it to that variable –using the new operator.

The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it.This reference is the address in memory of the object allocated.

ob

ob.png

Assigning Object References:


Box big = new Box();

Box small = big;

bb.png

Static Keywords in Java

  • When a member is declared static, it can be accessed,
    –before any objects of its class are created –without reference to any object
  • Both methods and variables can be declared static.
  • main( ) is declared as static because it must be called before any object exist.
  • Instance variables and methods are called so because they belong to objects.
  • Every time an object is created, a new copy of each of them is created.
  • Static variables are essentially global variables.
  • When objects of its class are declared, no copy of a static variable is made.
  • Instead, all instances of the class share the same static variable.

Methods declared as static have several restrictions:


•They can only call other static methods

•They must only access static data

•They cannot refer to this or super in any way.

EXAMPLE:


class UseStatic{

static int a = 2;

static int b;

static void meth(int x) {

System.out.println(“x = ” + x);

System.out.println(“a = ” + a);

System.out.println(“b = ” + b);

}

static {

System.out.println(“Static block initialized.”);

b = a * 4;

}

public static void main(String args[]) {

meth(42);

}

}

OUTPUT:

x=42

a=2

b=8

Constructor in Java

  • Constructor in java is a special type of method that is used to initialize the object.
  • Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as a constructor.

Rules for creating Java constructor 

 

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of Java constructors


There are two types of constructors:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

java-constructor.png

  1. Default constructor (no-arg constructor)


  • When we do not explicitly define a constructor for a class, then Java creates a default constructor for the class.
  • Default constructor automatically initializes all instance variables to zero.
  • Once we define our own constructor, the default constructor is no longer provided.

Syntax of default constructor:


 <class_name>(){ }

Example of default constructor:


class Bike{

    Bike(){

       System.out.println(“Bike is created”);

                }

   public static void main(String args[]){

Bike b=new Bike();

}

}

OUTPUT:

Bike is created

2. Parameterized constructor

  • A constructor that have parameters is known as parameterized constructor.
  • Parameterized constructor is used to provide different values to the distinct objects.

class Student{

int id;

String name;

 

Student(int i,String n){

id = i;

name = n;

}

void display(){System.out.println(id+” “+name);}

public static void main(String args[]){

Student s1 = new Student(1,“Ramu”);

Student s2 = new Student(2,“Shamu”);

s1.display();

s2.display();

}

}

Output:
1 Ramu
2 Shamu

this Keyword in Java

  • There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.

Usage of java this keyword:


  1. this can be used to refer current class instance variable.
  2. this can be used to invoke current class method (implicitly)
  3. this() can be used to invoke the current class constructor.
  4. this can be passed as an argument in the method call.
  5. this can be passed as an argument in the constructor call.
  6. this can be used to return the current class instance from the method.

EXAMPLE:


Understanding the problem without this keyword

stu.png

Output:
0 null 0.0
0 null 0.0

Solution to the above problem by this keyword


stu.png

output:

111 ankit 5000

112 sumit 6000

Inheritance in Java

  • Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of the parent object.
  • The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class, and you can add new methods and fields also.
  • Inheritance represents the IS-A relationship, also known as a parent-child relationship.

Why use inheritance in Java


  • Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Syntax of Java Inheritance


 

class Subclass-name extends Superclass-name

{

//methods and fields

}

  • The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of “extends” is to increase the functionality.
  • In the terminology of Java, a class which is inherited is called a parent or super class and the new class is called child or subclass.

Java Inheritance Example:


inheritance.jpg

  • As displayed in the above figure, Programmer is the subclass and Employee is the superclass. A relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.

emp.png

OUTPUT:

Programmer salary is:40000.0

Bonus of programmer is:10000

Types of inheritance in java


typesofinheritance.jpg

Note: Multiple inheritances is not supported in java through class.

Single Inheritance Example


File: TestInheritance.java

 

class Animal{

void eat(){System.out.println(“eating…”);}

}

class Dog extends Animal{

void bark(){System.out.println(“barking…”);}

}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}

Output:

barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java

 

class Animal{

void eat(){System.out.println(“eating…”);}

}

class Dog extends Animal{

void bark(){System.out.println(“barking…”);}

}

class BabyDog extends Dog{

void weep(){System.out.println(“weeping…”);}

}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

 

class Animal{

void eat(){System.out.println(“eating…”);}

}

class Dog extends Animal{

void bark(){System.out.println(“barking…”);}

}

class Cat extends Animal{

void meow(){System.out.println(“meowing…”);}

}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Output:

meowing...
eating...

Why multiple inheritance is not supported in java?


  • To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
  • Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call a method of A or B class.
  • Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have the same method or different, there will be compile time error now.

super keyword in java

  • The super keyword in java is a reference variable which is used to refer immediate parent class object.
  • Whenever you create the instance of a subclass, an instance of the parent class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword


  1. super can be used to refer immediate parent class instance variable.
  2. super can be used to invoke immediate parent class method.
  3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of the parent class. It is used if parent class and child class have same fields.

 

class Animal{

String color=“white”;

}

class Dog extends Animal{

String color=“black”;

void printColor(){

System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal class

}

}

class TestSuper1{

public static void main(String args[]){

Dog d=new Dog();

d.printColor();

}}

Output:

black
white
  • In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

class Animal{

void eat(){System.out.println(“eating…”);}

}

class Dog extends Animal{

void eat(){System.out.println(“eating bread…”);}

void bark(){System.out.println(“barking…”);}

void work(){

super.eat();

bark();

}

}

class TestSuper2{

public static void main(String args[]){

Dog d=new Dog();

d.work();

}}

Output:

eating...
barking...
  • In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local.
  • To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let’s see a simple example:

class Animal{

Animal(){System.out.println(“animal is created”);}

}

class Dog extends Animal{

Dog(){

super();

System.out.println(“dog is created”);

}

}

class TestSuper3{

public static void main(String args[]){

Dog d=new Dog();

}}

Output:

animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

Polymorphism in Java

  • When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
  • In java, we use method overloading and method overriding to achieve polymorphism.
  • Another example can be to speak something e.g. cat speaks meow, dog barks woof etc.
  • ju.gif

Method Overloading in Java


  • If a class has multiple methods having the same name but different in parameters, it is known as Method Overloading.
  • If we have to perform only one operation, having the same name of the methods increases the readability of the program.
  • Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int, int) for two parameters, and b(int, int, int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
  • So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

  1. By changing number of arguments
  2. By changing the data type

NOTE: In java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don’t need to create instance for calling methods.

class Adder{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

}

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

Output:

22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.

class Adder{

static int add(int a, int b){return a+b;}

static double add(double a, double b){return a+b;}

}

class TestOverloading2{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Output:

22
24.9

Why Method Overloading is not possible by changing the return type of method only?


In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let’s see how ambiguity may occur:

class Adder{

static int add(int a,int b){return a+b;}

static double add(int a,int b){return a+b;}

}

class TestOverloading3{

public static void main(String[] args){

System.out.println(Adder.add(11,11));//ambiguity

}}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

Method Overriding in Java


  • If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
  • In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


  • Method overriding is used to provide the specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding method


  1. must have the same name as in the parent class
  2. method must have the same parameter as in the parent class.
  3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding


Let’s understand the problem that we may face in the program if we don’t use method overriding.

class Vehicle{

void run(){System.out.println(“Vehicle is running”);}

}

class Bike extends Vehicle{

public static void main(String args[]){

Bike obj = new Bike();

obj.run();

}

}

Output:

Vehicle is running

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

class Vehicle{

void run(){System.out.println(“Vehicle is running”);}

}

class Bike2 extends Vehicle{

void run(){System.out.println(“Bike is running safely”);}

public static void main(String args[]){

Bike2 obj = new Bike2();

obj.run();

}

Output:

Bike is running safely

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details, for example, sending SMS, you just type the text and send the message. You don’t know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction


There are two ways to achieve abstraction in java

  1. Abstract class (0 to 100%)
  2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

abstract class A{}


abstract method

A method that is declared as abstract and does not have implementation is known as an abstract method.

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.

 

abstract class Bike{

abstract void run();

}

class Honda4 extends Bike{

void run(){System.out.println(“running safely..”);}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

}

}

OUTPUT:

running safely..

Encapsulation in Java

  • Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, capsule i.e. mixed of several medicines.

Red-Hearts-in-a-Capsule-1920x1200-wide-wallpapers.net.jpg

  • We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
  • The Java Bean class is the example of fully encapsulated class.

An advantage of Encapsulation in java


By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.

Simple example of encapsulation in Java

Let’s see the simple example of encapsulation that has only one field with its setter and getter methods.

 

//save as Student.java

package com.java;

public class Student{

private String name;

 

public String getName(){

return name;

}

public void setName(String name){

this.name=name

}

}

 

//save as Test.java

package com.java;

class Test{

public static void main(String[] args){

Student s=new Student();

s.setName(“vijay”);

System.out.println(s.getName());

}

}

 

NOTE:

Compile By: javac -d . Test.java

Run By: java com.java.Test

Output: vijay

Interfaces in Java

  • Using interface, we can fully abstract a class’ interface from its implementation

This means, we can specify what a class must do, but not how it does it.

  • Interfaces are syntactically similar to classes but there

 

–Methods are abstract

–Fields are final

  • Once defined, any number of classes can implement an interface

 

Also, one class can implement any number of interfaces.

Defining Interfaces:


interface InterfaceName

{

variables declaration;

methods declaration;

}

Variables are declared as:

static final typevariableName= value;

Methods are declared as:

Return-type methodName(parameter_list);EXAMPLE:


interface Product

{

static final intcode = 1001;

static final String name = “Fan”;

void display ();

}

interface Area

{

static final float pi = 3.142F;

float compute (float x, float y);

void show ();

}

Implementing Interfaces:


class classnameimplementsinterfacename

{

//body of classname

}

class classnameextendssuperclass

implements interface1, interface2, …

{

//body of classname

}

 

Advertisements

One thought on “CORE JAVA: OOPs (Object Oriented Programming System)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s