Alphalearningschool
        

<<< Prev

Next >>>

Up
OOP CONCEPTS

Below mentioned topics are the OOPS concepts

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

Let’s see an Explanation of all the above mentioned OOP Concepts

Object: An object is a program construct that falls under a ‘classification’ (of a class) which has state and behavior.

Initializing the object:

 

Public class Point {

     public int x = 0;

     public int y = 0;

      //constructor

     public Point(int a, int b) {

         x = a;

         y = b;
    }

      } 

                            } 

Let’s see an example of Object now:

 

 

Class:  A class is a specification or blue print    or template of an object that defines what goes to make up a particular sort of object.

For Example: Employee is an example of a class

A specific employee with unique identification is an example of an object.

 

              Class Employee {

                    //instance variable declaration

                      //method declaration


                                              }

Below diagram will explain the structure of class:

Inheritance: 

The process of creating a new object by obtaining type, properties & behaviours of an existing object called inheritance. We can reuse the existing object properties and behaviours with our new object reference

                                                            ( Or) 

The process of defining new object upon an existing object functionality by obtaining existing object type, properties & behaviours to new object and then further we can reuse  existing properties of an object & extends its functionality to next level is called inheritance.   

                             

Why inheritance? 

When we find new object with the same properties and behaviours of an existing object, we must develop inheritance between these two objects. So that new object will be treated as an existing object type, then where ever exiting object type referenced variable is used as method parameter there we can pass this new object as argument. 

Advantages of inheritance 

  • Reusability
  • Runtime polymorphism(or dynamic binding)
  • Through this inheritance derived class and user class will get the advantage as code redundancy is reduced, reusability is increased, can override existing functionality, extend existing functionality, implement new functionality. 

Inheritance implementation in JAVA 

Inheritance can be implemented in JAVA using below two keywords 

  1. extends
  2. implements 

“extends”          is used for developing inheritance between two classes or two interfaces.

“implements”  is used for developing inheritance between interface, class. 

Syntax: 

Class A {}                                                                             interface |1{}

class B extends A{}                                                    interface extends |1{}

                                                                                      class C implements |1{}

 

Polymorphism:  

Polymorphism has two words: Poly              - many/multiple

                                                Morphism     -   form      

As per real –world polymorphism refers to an object exhibiting multiple behaviours in the same operation.  For Example a person will exhibit   different feelings based on the given news. For good news he will exhibit happy feeling, for bad news he will exhibit sad feeling. Exhibiting these different expressions for the feeling operation is nothing but polymorphism. 

 The process of defining a method with multiple implementations for exhibiting different behaviours of the object in the same operation is called polymorphism.  

//News.java 

class News{

 void feeling(){

    System.out.println("feel something");

          }

     } 

//GoodNews.java

Class GoodNews extends News{

   Void feeling(){

   System.out.println("Happy feeling-Smiling-J");      }

} 

//BadNews.java

Class BadNews extends News{

   Void feeling (){

   System.out.println("Sad feeling-L");

     }

}

 

Abstraction

In general abstraction means hiding an object operation implementation details from the user and providing only the necessary details to access the object operation is called abstraction.

                                    (or)

Abstraction: Is the mechanism to

  1. Hide the unnecessary things from user so providing easiness.
  2. Hiding the internal implementation of software so providing security. 

 It can be implemented in 2 ways.

  1. Interface
  2. Abstract Class 

For Example:

  1. Keyboard operations are abstracted- means when we type a key we do not know how characters are transferred and displayed on notepad file.
  2. TV remote is an object. Users are provided with only interface which is nothing but keys. Users only know which key to press for what function. User will not know what happens inside when we press the key. 

Advantages of abstraction:

  • Hiding the bigger picture of object from the user and to make the object operations with ease.
  • Parallel development of user class and interface class.
  • The interface creates a contract between the client and the implementer.
  • Abstraction makes code as readable and more simpler. Because complexity of code will be hidden.
  • Abstraction makes code from longer to small, because abstraction doesn't show unnecessary things.

 

 Encapsulation

  The process of creating a class by binding variables and methods as one unit, and then operating variables only through these methods is called encapsulation.

                                                         (or)

 Is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.

             Encapsulation = Data Hiding + Abstraction.

It can be developed by:

  1. Declaring all variables as private.
  2. By defining one pair of public setter and getter methods 

For Example:

  • Every time you log into your email account( Gmail, Yahoo, Hotmail or official mail), you have a whole lot of processes taking place in the backend, that you have no control over. So your password would probably be retrieved in an encrypted form, verified and only then you are given access. You do not have any control, over how the password is verified, and this keeps it safe from misuse.
  • Wrapping up of properties and behaviour in to a single unit and class is best example of encapsulation. 

Advantages of encapsulation:

  • Data Hiding – Encapsulation in Java, provides the programmer to hide the inner classes and the user to give access only to the desired codes. It allows the programmer to not allow the user to know how variables and data are stored. 
  • Flexibility – With Java encapsulation, we can make the data as read-only or write-only as we require it to be. 
  • Reusability – It allows the user to a programmer to use the program again and again.
  • Testing of the code – Ease of testing becomes easy.

 

 

Differences b/w Object oriented programming and procedure oriented programming

 

 

            procedure oriented programming

                   Object oriented programming

It is meant for developing  mathematical operations

It is meant for developing business operations

programs are developed around an operation

Programs are developed around an object and its data

Programming style is "functional based"

Programming style is "class based"

It doesn’t provide security to data because it doesn’t  support accessibility modifier & encapsulation

It provides security to data because it supports accessibility modifier and encapsulation

Its programs are static in nature , means cannot change from one program to another program of same type  at run time because it doesn’t supports inheritance

Its programs are dynamic in nature , means we can  change from one program to another program of same type  at run time because it  supports inheritance

 

Java naming conventions

Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier—for example, whether it’s a constant, package, or class—which can be helpful in understanding the code. 

Note: Code conventions improve the readability of the software. This allows engineers to understand new code more quickly and thoroughly. 

     Packages Names 

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. 

The example package prefix here is org.banana. Subsequent components of the package name vary according to an organization’s own internal naming convention. 

The following are a few examples of correct package names.

org.banana.slimy

org.banana.furry.fruit 

Class and Interface Names 

  • Class and interface names should be nouns.
  • Class and interface names should be written in mixed case with all words capitalized. In situations where one of the words is comprised entirely of capital letters (e.g., an acronym) the following word should still follow the rule of also starting with a capital letter.
  • Class and interface names should be simple and descriptive. Use whole words and avoid acronyms or abbreviations — unless the abbreviation is much more widely used than the long form, such as URL or HTML.
  • Class and interface should not contain prefixes to differentiate them from third-party classes.

          class Raster

          interface RasterDelegate

          class ImageSprite

          interface Storing

          class CSharp

          interface HTMLParser

Method Names 

  • Method names should be verbs.
  • Method names should be written in mixed case; the first word completely in lowercase and the first letter of each subsequent word capitalized. In situations where one of the words is a comprised entirely of capital letters (e.g., an acronym) the following word should still follow the rule of also starting with a capital letter.
  • Method names should be simple and descriptive. Use whole words and avoid acronyms or abbreviations — unless the abbreviation is much more widely used than the long form, such as URL or HTML.
  • Methods names that are for accessors should be prefaced by get and mutators should be prefaced by set (g., getPhoneNumber or setPhoneNumber). 

             The following are examples of proper usage for naming methods. 

             this.swim ();

             this.climbUpTree ();

             aMonkey.isHungry ();

             aMonkey.getBanana ();

             this.htmlRedirect ();

             aScore.playCSharp ();

             this.getURLProtocol ();

 

Variable Names 

Variable names — local, instance, and class variable names — should adhere to the following conventions.

  • Variable names, in general, should be nouns.
  • Variable names should be written in mixed case; the first word completely in lowercase and the first letter of each subsequent word capitalized. In situations where one of the words is a comprised entirely of capital letters (e.g., an acronym) the following word should still follow the rule of also starting with a capital letter.
  • Variable names should be simple and descriptive. Use whole words and avoid acronyms or abbreviations — unless the abbreviation is much more widely used than the long form, such as URL or HTML.
  • Variable names should not start with an underscore ( ) or dollar sign ($) character, even though both are allowed in Java.
  • Single-character variable names should be avoided except for temporary “throwaway” variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters. 
  • Variables that hold boolean values should be named such that they represent interrogative statements (e.g., isRunning or fContainsPoint). 

The following are examples of proper usage for naming variables.

 //local variable declarations

 int i = 0; char c = ’x’;

float myWidth = 5.25;

boolean isClimbing = true; 

// instance variable declarations private

      int fCount = 1;

      private int fX = 0;

     private int fY = 1;

     private boolean fIsHungry = false; 

 // class variable declarations

 private static String sName = new String("MonkeyBoy");

private static Object sRef = null;

Constant Names 

The names of variables declared class constants (static final) and of ANSI constants should be all uppercase with words separated by underscores ( ). (ANSI constants should be avoided, for ease of debugging.)

The following are several examples of proper naming of constants. 

 static final int MIN_BANANA_COUNT = 12;

static final int MAX_BANANA_COUNT = 999;

static final String DEFAULT_NAME = new String("MonkeyBoy");

Constructor in Java

A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that is used to initialize instance variables of an object before the reference of this object is returned by new. Constructor can be defined as a method having same name as class name without any return type. 

Constructor is different from method in two ways 

  1. It has a same name as the class whose instance variables are they initialize.
  2. Constructor is automatically called by compiler whenever the object of the class is created so because of this constructor doesn’t have return type, not even void 

class Example {  Example () {        // constructor body           }}

Here, Example () is a constructor; it has same name as that of the class and doesn’t have a return type. 

class Example {    void Example () {       // method body   }}

Here, Example () has same name as that of the class. However, it has a return type void. Hence, it’s a method not a constructor.

Example of constructor 

public class Display {       

               String name;

               //Constructor

               Display (){

                  this.name = "Aplhalearningschool.com";

               }

               public static void main(String[] args) {

                  Display obj = new Display ();

                  System.out.println(obj.name);

               }

            } 

Output: 

Aplhalearningshool.com 

 In this example we have used this keyword, which refers to the current object, object obj in this example and also new keyword creates the object of Display () and invokes the constructor to initialize the created object.

 

Types of Constructors 

There are three types of constructors: Default, No-arg constructor and Parameterized.

 

Default constructor 

   Purpose: is to enable  to create object of class type

When an object is created, a constructor is always invoked. But in some programs even if we don’t create constructor, So in that situation the compiler automatically creates one constructor which is called as default constructor.  It does not contain any parameters and doesn’t even contain any statements in its body. 

 

Syntax:

class className{    className(){ // default constructor    ...   }}                                   

 

Example 

class Defaultconstructor {

                double width;

                double height; 

                Defaultconstructor() {

                  width = 10;

                  height = 10;

                } 

                double area() {

                  return width * height;

                }             

                public static void main(String args[]) {

                       Defaultconstructor mybox1 = new Defaultconstructor();

                  double area;

                  area = mybox1.area();

                  System.out.println("Area is " + area); 

                }

              }

 

 

Output: 

Area is 100.0

If you don't declare a default constructor the Java compiler will add one for you. When you call the default constructor added by Java compiler the class member variables are initialized by default value. If you do provide a default constructor the Java compiler would not insert one for you. 

2.

class Rectangle {

 double width;
 double height;

 double area() {
  return width * height;
 }
}

public class Oprator {
 public static void main(String args[]) {
  Rectangle mybox1 = new Rectangle();
  double area;
  area = mybox1.area();
  System.out.println("Area is " + area);
 }
}

Output:

Area is 0.0

Here we remove the default constructor from class Rectangle. When we compile the class Java compiler adds the default constructor for us so we can still construct a Rectangle object by calling the default constructor. But the value of width and height would be initialized to 0.0.

No- arg constructor 

Purpose: is to call the superclass constructor.

We can create our constructor with no arguments is known as no-arg constructor.

The variables are initialized to their default values belonging to their class types (primitive data types). 

Example:

 

class Noargconstructor

{

     public Noargconstructor ()

     {

         System.out.println("This is a no argument constructor");

     }

     public static void main(String args[]) {

       new Noargconstructor();

     } 

Output: 

This is a no argument constructor 

Parameterized constructor 

A constructor that has parameters is known as a Java parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at time of their creation It may be necessary to initialize the various data elements of different objects with different values when they are created. This is achieved by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors 

 

Example: 

public class Oprator {
	String carColor;

	Oprator(String carColor) {
		this.carColor = carColor;
	}

	public void disp()    {       
		
		System.out.println("Color of the Car is : "+carColor); 
		}
	

public static void main(String args[])   
{   
	//Calling the parameterized constructor
    Car c = new Car("Blue"); c.disp();    
	}
}

 

Output: 

Color of the Car is : Blue

Constructor overloading in java 

 Defining multiple constructors in a class with different parameters type/list/order is called constructor overloading.  Constructors can also be overloaded but they cannot be overridden. Because these are not inherited, also we cannot create constructor in subclass with super class name. 

Execution: To execute overloaded constructor we must pass that constructor parameter type argument in the object creation statement as shown below. 

For Example 

class Constructoroverloading {

Constructoroverloading() {

       System.out.println("Ex No-arg constructor");

       }

Constructoroverloading(int a) {

       System.out.println("Ex int-arg constructor");

}

Constructoroverloading(String str) {

       System.out.println ("Ex String-arg constructor");

}
       } 

   public static void main(String []args) {    

        Constructoroverloading c1= new Constructoroverloading ();

        Constructoroverloading c2= new Constructoroverloading (10);

        Constructoroverloading c3= new Constructoroverloading("abc");

      }     

  }

 

Two cases of overloading constructor 

  1. 1. To define different object initialization logic.
  2. To execute the same initialization logic by taking input values in different types. 

Example of Constructor overloading

class Box

            {

               double width, height,depth;

               Box(double w, double h, double d)

              {

width = w;

height = h;

depth = d;

}

   double volume() {

  return width * height * depth;

}

          

 

Since Box( ) requires three arguments, it’s an error to call it without them. , the solution to these problems is quite easy: simply overload the Box constructor so that it handles the situations just described. Here is a program that contains an improved version of Box that does just that

class Box

      {

       double width, height, depth;

       Box(double w, double h, double d)

      {

         width = w;

         height = h;

         depth = d;

      }

      Box()

      {

         width = height = depth = 0;

      }

      Box(double len)

      {

         width = height = depth = len;

      }

      double volume()

      {

         return width * height * depth;

       }

      }

      public class Test

      {

      public static void main(String args[])

      {

      Box mybox1 = new Box(10, 20, 15);

      Box mybox2 = new Box();

      Box mycube = new Box(7);

      double vol;

            vol = mybox1.volume();

            System.out.println(" Volume of mybox1 is " + vol);

            vol = mybox2.volume();

            System.out.println(" Volume of mybox2 is " + vol);

            vol = mycube.volume();

            System.out.println(" Volume of mycube is " + vol);

            }

       }

}

 

Output: 

Volume of mybox1 is 3000.0

Volume of mybox2 is -1.0

A volume of mycube is 343.0

 

Differences

Differences between Constructor and methods             

Constructors

Methods

Constructor is used to initialize an object

Method is used to exhibits functionality of an object.

Constructors are invoked implicitly 

Methods are invoked explicitly.

Constructor does not return any value

Method may/may not return a value.

In case constructor is not present, a default constructor is provided by java compiler

In case of the method, no default method is provided.

A constructor should be of the same name as that of class

Method name should not be of the same name as that of class.

Constructor cannot be a final, abstract, static and synchronized

Method can be final, abstract, static and synchronized.

 

Difference between Abstract class and Interface

 

Abstract class

Interface

It is a partial abstract class, it allows us to define both concrete and abstract methods.

It is pure abstract class, it allows us to define only abstract methods. From Java 8 onwards we can define concrete default & static methods

When we want to implement some of other operations of an object common to all its sub types and want declare some of the other operations to be implemented by sub types programmers as per their requirement we must use abstract class

When we want to only declare all operations of an object and informing to other programmers to implement these operations as per its subtype requirements we must use interface

It provides both reusability and forcibility

It provides only forcibility

It should be declare as abstract using abstract keyword, abstract methods also should contain abstract keywords

Declaring it as abstract is optional, also declaring its methods as abstract is optional. Compiler places abstract keyword at compilation time

Its default accessibly modifier is package, can be changed to public

Its default accessibly modifier is also package, can be changed to public

Its members default accessibly modifier is package, can be changed to any of other three accessibility modifiers

Its members default accessibly modifier is public, cannot be changed

Its variables are not by default static and final

Its variables are by default static and final

Static final variables no need to be initialized at the time of creation, but should be initialized in any one of the static blocks

In interface, variables should be initialized at the time of creation as there are no static blocks

Inheritance relation is established using

“extends" keyword

Inheritance relation is established using "implements “keyword

It can have inner class

It can also have inner class



Java Keywords 

The Java programming language has total of 50 reserved keywords which have special meaning for the compiler and cannot be used as variable names and let’s have a look of few of them.

 

Keyword

Explanation

abstract

The abstract keyword is a modifier that is used when abstract methods and abstract classes are declared. A class that contains an abstract method is an abstract class that serves as a base class for other classes. An abstract class cannot be instantiated

 boolean

This keyword identifies the boolean type that can get values true and false

break

With a break statement it is possible to break out from a loop or a switch-case construct. I recommend that break statements should be used only in switch-case constructs. Using a break statement inside a loop is not logical. By using state variables it is possible to avoid break statements inside loops.

catch

Keywords catch, finally, throw, throws, and try are needed when exceptions are handled in Java programs. Exceptions are "error objects" which Java programs can throw and catch in problem situations. catch begins the catch block of a try-catch(-finally) construct

char

This keyword specifies the built-in (variable) type that has 16 bits, and can store the Unicode character code of a character.

continue

A continue statement inside a loop causes a jump to the end of the internal statements of the loop. continue statements have not been studied in this book, and I recommend that they should not be used in programs because they are similar to goto statements. Instead of continue statements, more logical program constructs like if constructs should be favored

default

This keyword is used inside switch-case constructs to identify the default case

 final

This keyword specifies that a local variable or a field is a constant whose value may not change. In addition, the final keyword can specify that a class is a "sealed" class from which it is not possible to derive new classes, or it can specify that a method may not be overridden in derived class

implements

The implements keyword is used when a class implements one or more interfaces

instanceof

A relational operator with which it is possible to check if something is of certain type. The instanceof operator returns true when the type of its left operand is the type specified by the right operand, or when the type of the left operand is derived from or implements the type specified by the right operand.

interface

A keyword that begins an interface declaration. When a class implements an interface, it provides implementations for the methods that are specified in the declaration of the interface.

static

A keyword to specify that a method or a field is static. A static method can be called without creating an object of a class. A static field is shared by all objects of a class

synchronized

The synchronized keyword can be used in programs which run several threads simultaneously, and in which a method is called from several threads. When a method is declared with the synchronized keyword, only one thread at a time can use it

this

When the this keyword is used inside a method, it references the object for which the method was called. With the this keyword, a constructor can call another constructor of the same class.

transient

A field of a class can be marked with the transient keyword to indicate that its value does not need to be stored when an object of the class is serialized. Serialization of objects means that the data stored in an object is converted to such a form that it is easy to store it

super

With the super keyword it is possible to call the constructors and polymorphic methods of the superclass

 

 

Similarities and differences between this and super keywords

 

this (current class)

super class

It is a keyword used to store current object reference

It is a keyword used to store super class non-static member's reference sub class object

Pre define instance variable used to hold current object reference

Pre defined instance variable used to hold super class memory reference through subclass object

Used to separate state of multiple objects of same class and also used to separate local variables and class level variables in a non-static method if both has same name

Used to separate super class and subclass members if both have same name

It must be used explicitly if non-static variable and local variable or parameter name is same.

It must be used explicitly if super class and sub class members have same names

 

Can't be referenced from static context. It can be printed, means can be called from Sopln() from non -static context.                                                                            System.out.println (this);  System.out.println(Example.this);

Can be referenced from static context. It can't be printed, means cannot be called from Sopln() from non -static context.                                                                            System.out.println (super);  System.out.println(Example.super);              System.out.println(this.super);

 

Difference between private method and final method

Private method

final method

We cannot override private method. If we override ,compiler will not throw error, but it will be treated as sub class own method

We cannot override final method.If we override, compiler will throw error, final method cannot override

private method will not inherit to sub class

final method will inherit to sub class

We cannot call private method in sub class, compiler will throw error, because it is not inherited

final method we can call in sub class, because it is inherited to sub class