concept – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 27 Aug 2022 15:14:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg concept – Programmerbay https://programmerbay.com 32 32 Why Multiple Inheritance is Not Supported in Java https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/ https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/#respond Fri, 26 Aug 2022 07:34:33 +0000 https://programmerbay.com/?p=5824 In this article, we’ll be discussing what is use of inheritance and why multiple inheritance is not supported in Java .

One of the main features of object-oriented programming is Inheritance. In Java, Inheritance can be defined as a way by which a class acquires properties from another class.

A class which inherits properties from another class is known as subclass or child class, while the class which is inherited, is termed as superclass or parent class. extends keyword is used in order to inherit the properties of another class.

Syntax:

class SubClass extends ParentClass { 
// Attributes and behavior 
}

As and when, a class uses extends keyword, it can access and include all data members and member functions of the inherited class . However, a child class can never access and inherit the private members of parent class.

Why we use Inheritance in Java ?

Inheritance provides a number of features:

  •  Code Reusability:

Code reusability means an existing class can be reused in other class, specifically for similar type of classification.

  • Ease to add new feature:

One can provide new functionality to a new class by using the existing class without changing it.

  • Overriding

This provides the freedom of having methods with the same signature as in parent class but with meaningful implementation.

Why Multiple Inheritance is Not Supported in Java?

Multiple Inheritance is a type of inheritance in which a class extends two or more classes.
Unlike C++, Java doesn’t support multiple inheritance.

The reason because multiple inheritance raises ambiguity problem which creates the possibility of inheriting multiple copies or generating multiple paths of same data for child class.

In other words, a compiler can’t able to determine which member to choose if inheriting classes have common members. This problem is termed as Diamond Problem.

image 2020 12 27 141335
Figure: Diamond Problem in Inheritance

 

For example, suppose a class represents Person having getGender() method and this Person Class is inherited by Man and Woman Class. Since both have inherited getGender() method from Person Class.

However, if Man and Woman Class is further extended by another class named Programmer. As a result, the Programmer Class would get two copies of “getGender()” method which leads to ambiguity for compiler. Meaning, a compiler won’t be able resolve method call at runtime.

Program to show the concept of Inheritance

class A
{
int a;
A() // constructor
{
a=10;
}
void display() // method
{
System.out.println("I am here with "+ a);
}
}

class B extends A{ // inheriting
void show()
{
display();
}
}
public class Inheritanceuseing {
public static void main(String[] args) {
B obj = new B();
obj.show();
}

}

]]>
https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/feed/ 0
Static Keyword in Java with Example https://programmerbay.com/what-are-the-use-of-static-keyword-in-java/ https://programmerbay.com/what-are-the-use-of-static-keyword-in-java/#respond Tue, 25 Aug 2020 08:49:12 +0000 https://www.programmerbay.com/?p=4784 What is a static keyword in Java?

static keyword in javaJava provides a special type of member which doesn’t depend on the instance of a class.

These members execute independently without using class instance.

To create such members Java supports a static keyword that allows them to get executed before object creation.

A Static keyword can be imposed on both methods and variables.

The main method is a classic example of a static keyword that doesn’t need to the object for execution instead it runs before an instance is created.

How to access static variable or method ?

To access a static variable or to invoke a static method dot operator is used with the class name to which that particular variable or method belongs.

Points to remember:

  • Only a single copy is created and used in case of static variable
  • An object is not needed to access static variable and method
  • Run before the creation of an object
  • We can’t declare constructors as static
  • A class cannot be declared as static, though Java allows an inner class to be defined as static
  • Using static with the final keyword on a variable, create constant

Static keyword can be used with:

  1. Variables
  2. Methods
  3. Blocks or initializers
  4. Inner class
  • Java Static Variable

When a variable is declared with the static keyword, it acts like a global variable.

In other words, All the objects share the same variable which gets a single copy in memory, unlike instance variable which gets memory each time when a new object is made.

Static variables initialized with the same default values as instance variables do.

Syntax:

static dataType variableName;
  • Java Static method with example

When a method is preceded with a static keyword then it can only access static variables and call the static method right away.

It doesn’t allow this or super keyword as they are references of superclass or subclass.

A static method can be invoked using the class name.

For example, className.static_method(). static methods cannot be overridden.

Syntax:

static return_type method_name(){ 
//body 
}

Java program to show the working of static method:

public class Test
{				//Static variable 
  static int y;
    Test ()
  {
    System.out.println ("Hi!I am constructor");
  }				// Static method to access static variable 
  static void example ()
  {
    y = 10;
    System.out.println ("Hi! I am static and can access static variable =" +
      y);
  }
  public static void main (String[]args)
  {
    Test obj = new Test ();
    Test.example ();
  }

}

Output:

Hi!I am constructor
Hi! I am static and can access static variable = 10
  • Java Static block with example

When a pair of curly braces is followed by a static keyword, then it is referred to as static initializer or static initialization block.

It executes only once for respective class, rather then for every object.

As the name suggests it is used to initialize static data members only. These types of blocks don’t have return statement and can’t throw checked exceptions.

Syntax:

static{ 
//static variable initializer 
}

Java program to show the working of static block:

public class Test
{
  //Static variable 
  static int y;
    Test ()
  {
    System.out.println ("Hi!I am constructor");
  }				// Static block to initialize variable 
  static
  {
    y = 10;
    System.out.println ("I am static Initializer = " + y);
  }
  public static void main (String[]args)
  {
    Test obj = new Test ();
  }

}

Output:

I am static Initializer = 10
Hi!I am constructor
  • Java Static Nested Class with example

There is a concept of nested class which can be defined as a class when declared within another class is known as a nested class and when this nested class is preceded with a static keyword then it is said to be a static nested class.

In other words, a static nested class is a static member of the outer class.

It doesn’t require to wait for the instantiation of an object of the outer class which means we can create an object of static inner class independently.

  • A static nested class can have static or nonstatic members.
  • A static member of an outer class can be accessed by the methods of static inner class whereas non-static can’t be accessed directly. However, it can be possible by using the reference of the outer class.

Syntax:

class A
{
  static class B
  {
      
  }

}

Java program to show the working of static nested class:

public class Test
{

  //Static variable 
  static int y;
  // constructor 
    Test ()
  {
    System.out.println ("Hi!I am constructor");
  } static class nestedClass
  {
    void display ()
    {
      System.out.println ("I am from static nested class");
    }

  }
  public static void main (String[]args)
  {
    Test obj = new Test ();
    Test.nestedClass o = new Test.nestedClass ();
    o.display ();
  }

}

Output:

Hi!I am constructor
I am from static nested class

Java Program to demonstrate Working of static keyword

Program:

class Test
{

  static int y;			//Static variable 

    Test ()			// constructor 
  {
    System.out.println ("Hi!I am constructor");
  }

  static class nestedClass	//Nested static class 
  {
    void display ()
    {
      System.out.println ("I am from static nested class");
    }

  }

  // Static block to initialize variable static

  {
    y = 10;
    System.out.println ("I am static Initializer = " + y);
  }

  static void example ()	// Static method to access static variable 
  {
    y = 10;
    System.out.println ("Hi! I am static and can access static variable =" +
      y);
  }
  public static void main (String[]args)
  {
    Test obj = new Test ();

    Test.nestedClass o = new Test.nestedClass ();	// object of inner class 
    Test.example ();
    o.display ();
  }

}

Output:

Working of static keyword in Java with example output

]]>
https://programmerbay.com/what-are-the-use-of-static-keyword-in-java/feed/ 0
Lambda expression in Java 8 https://programmerbay.com/lambda-expression-in-java-8/ https://programmerbay.com/lambda-expression-in-java-8/#respond Sun, 14 Jun 2020 15:47:03 +0000 https://programmerbay.com/?p=6429 Lambda expression is one of the core feature introduced in Java 8 as it provides a way to achieve functional programming in an object oriented programming language. It is anonymous function without having modifiers and return type. In other words, it simply provides a definition to a single abstract method defined within an interface called as Functional interface.

Point to remember:

– It provides a way to achieve functional programming in Java

-A Lambda expression is anonymous function having no modifiers and return type.

– It uses functional interfaces as its base to implement functional programming in Java. Without functional interface it cannot be implemented.

-It uses arrow operator or lambda operator to tell the compiler it is a Lambda expression

Syntax:

lambda expressions

These are following features of a lambda expression:

another lambda
No return type: Unlike function, in lambda expression, we don’t provide the return type. We simply write () -> {}

No Modifiers: Another important aspect of Lambda expression is, no modifier is required to mention.

The above two aspects indirectly depends on abstract method of a functional interface. Lambda Expression indirectly references to that type.

Optional Argument type : It is not mandatory to provide datatype to the parameter, but if one does then parenthesis would be mandatory

Optional Parenthesis : if there is a single argument then putting parenthesis would be optional
Optional curly braces and return type : if there is a single statement in the expression body then there is no need to put curly braces and return statement(if have).

 

 

Before Lambda Expression:

create a function:

void cube(int x) {
System.out.println("cube :"+ x*x*x);

}

create an object to call that function:

Test obj = new Test();

Invoke it

obj.cube(3);

 

After Lambda Expression:

Import Function (A predefined functional interface)

import java.util.function.Function;

Create a Lambda expression:

Function<Integer,Integer> cube = x -> x*x*x;

call its apply abstract method

System.out.println("This is the cube of "+ x + ":"+ cube.apply(x));

]]>
https://programmerbay.com/lambda-expression-in-java-8/feed/ 0
Difference between final, finally and finalize in Java https://programmerbay.com/difference-between-final-finally-and-finalize/ https://programmerbay.com/difference-between-final-finally-and-finalize/#respond Sun, 01 Sep 2019 07:38:01 +0000 https://www.programmerbay.com/?p=4819 Java supports final, finally and finalize that are all completely used in different aspects. Final is a modifier that can be used with variables,methods and class to put restriction in various context, finalize is a method used to perform cleaning actions before destroying a particular object, and finally is a block used in companion with try (optional with try-catch).

final finally and finalize

Final Keyword

Final is the most common keyword which acts as a non-access modifier in the modern programming languages like C++, Java,etc.

The final keyword can be used along with variables, methods as well as with classes. They can be explained as follows:

  • Final variables

If the final keyword is used with the variable then, that variable becomes a constant.

eg:

final int i=10;

 

  • Final methods

If the method is declared with the final keyword then, that class method cannot be overridden even by its subclass.

eg:

class A{
int y;
// constructor
A(){
y=10;
}
final void display(){

System.out.println(" Value of y ="+y);

}
}


public class Test extends A
{
//error would be occurred
/* void display(){

System.out.println(" Value of y ="+y);
}*/

public static void main(String[] args) {
A obj = new A();
obj.display();
}

}

 

  • Final class

If the class is declared with the final keyword then, it cannot inherit any sub – class.

eg:

final class X{

// statements and methods

}

class Y extends X   // this will generate an error

{

//statements and methods

}

 

Finally Block

Finally is a block which comes into play when working with  Try / Catch block for handling exceptions. The finally block only executes after the try and catch blocks. The interesting fact about the finally block is that it will be executed whether there is an exception or not.

eg:   :

class test {

    public static void main(String[] args) {
 
        int x;
        try{
            x = 100/0;

        }finally {
            System.out.println("I am in finally block");
        }
    }
}

Output:

System.out.println("I am in finally block");

Finalize Method

This method is used to reallocate or free the system’s memory which was acquired by unused objects or unreachable objects. In Java, this whole process comes under the category of garbage collection.

eg:   :

class ABC{

int x=10;

protected void finalize() throws Throwable

{

System.out.println("from the finalize method");

}

}

 

Difference between final, finally and finalize is as follows:

  • GENERIC INFORMATION

If we consider the final, then it is a non-access modifier keyword for variables, methods, and classes used in modern programming; whereas; if we consider finally, then it is a type of block used in the exception handling; whereas; if we consider finalize, then finalize is basically a method of the Object Class.

  • USAGE

When we talk about final, then final is used as a keyword with the variables, methods and classes; whereas; when we talk about finally,

Then finally is a block which is used along with the try/catch block; whereas; when we talk about finalize, then finalize is a method only used with garbage collection, before Garbage collector destroys unreachable objects.

  • DETAILED DESCRIPTION

In case of the final, we have:

Final variables; these variables are constant and cannot be modified,

Final methods; these methods cannot be overridden by the child class’s methods,

Final class; these classes cannot be inherited to any subclass;

Whereas; in case of the finally, the finally block is the last step of the exception handling process; whereas; in case of finalize, the finalize is the method which performs the clean – up tasks which is held by object related to the object’s memory before the actual destruction of the objects.

  • THE EXECUTION

When we talk about final, then final method gets executed only after its call; whereas; when we talk about finally, then finally block is executed only after the execution of the try and catch blocks; whereas; when we talk about finalize, then finalize method is invoked just before the actual deletion or destruction of the object.

 

Key differences:

Basisfinal Keywordfinally Blockfinalize Method
DefinitionIt can be defined as a keyword whose association with a class, variable or method makes them immutable It can be defined as a block where one should write cleanup code such as closing network connections , database connections and moreIt can be defined as a method that allows us to perform some action before destroying a particular object
Refer toIt is a non-access modifier keyword used with variables, methods and classesIt is a type of block used in the exception handlingIt is basically a method of the Object Class
PurposeMakes a class, method or variable immutableCleanup codes and other important statements are put in this block and executed whether the exception occurs or notReleasing resources that is held by unreachable objects

]]>
https://programmerbay.com/difference-between-final-finally-and-finalize/feed/ 0