Showing posts with label Java Interface. Show all posts
Showing posts with label Java Interface. Show all posts

Monday, April 3, 2023

Java Concurrency: The Lock interface

Java Concurrency, Lock Interface, Oracle Java Certification, Java Guides, Java Prep, Java Preparation, Java Career, Java Skills, Java Jobs, Java Learning, Java Guides

Previously we implemented a thread safe counter using synchronized. We would like to swift from synchronized blocks to something more flexible with more features, this is were locks are of use. On this blog we will focus on Java’s Lock interface.

The Lock interface supports three forms of lock acquisition interruptible, non-interruptible, and timed.

We can acquire locks between threads. A thread will wait until the lock is released from the thread holding the lock:

@Test
    void lock() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            lock.lock();
            log.info("Acquired delayed");
            lock.unlock();
        });
 
        lock.lock();
        withDelayedLock.start();
 
        Thread.sleep(500);
        log.info("Will release");
        lock.unlock();
        withDelayedLock.join();
    }

Since the threads blocks on the lock we might as well interrupt the thread. In this case we can lock lockInterruptibly, and apply any logic in case of an Interrupt:

@Test
    void lockInterruptibly() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                log.error("interrupted while waiting",e);
            }
        });
 
        lock.lock();
        withDelayedLock.start();
        withDelayedLock.interrupt();
        lock.unlock();
        withDelayedLock.join();
    }

A thread can also try to acquire a lock which is already acquired, and exit immediately instead of blocking.

@Test
    void tryLock() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            boolean locked = lock.tryLock();
            assertFalse(locked);
        });
 
        lock.lock();
        withDelayedLock.start();
        Thread.sleep(500);
        lock.unlock();
        withDelayedLock.join();
    }

Also a time period can be specified until the lock is acquired.

@Test
    void tryLockTime() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            try {
                boolean locked = lock.tryLock(100, TimeUnit.MILLISECONDS);
                assertFalse(locked);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
 
        lock.lock();
        withDelayedLock.start();
        Thread.sleep(500);
        lock.unlock();
        withDelayedLock.join();
    }

Another thing of importance with locks is memory.

From the documentation

All {@code Lock} implementations <em>must</em> enforce the same
* memory synchronization semantics as provided by the built-in monitor
* lock, as described in
* Chapter 17 of
* <cite>The Java Language Specification</cite>:
*
<ul>*
    <li>A successful {@code lock} operation has the same memory
* synchronization effects as a successful <em>Lock</em> action.
*</li>
    <li>A successful {@code unlock} operation has the same
* memory synchronization effects as a successful <em>Unlock</em> action.
*</li>
</ul>

In order for the results to be flushed on the main memory we need to use lock and unlock.
Take the following example

private Lock lock = new ReentrantLock();
    private String threadAcquired = "main";
 
    @Test
    void wrongMemoryVisibility() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            lock.lock();
            try {
                threadAcquired = "delayed";
                System.out.println("Acquired on delayed");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
 
        });
 
        lock.lock();
        try {
            withDelayedLock.start();
            Thread.sleep(500);
        } finally {
            lock.unlock();
        }
 
        while (true) {
            System.out.println("Currently acquired " + threadAcquired);
            if (threadAcquired.equals("delayed")) {
                break;
            }
        }
 
        withDelayedLock.join();
        threadAcquired = "main";
    }

We print the variable threadAcquired by the main thread while it is changed by the thread with a Delayed lock.

After a few runs a situation where the threadAcquired variable has a stale value on the main thread will appear.

Acquired on delayed
Currently acquired main

We did this on purpose, on a real world problem we should not access variables like threadAcquired without proper synchronisation, for example we should have acquired the lock first, this way the memory would be synchronised and we would have an up to date value.

@Test
    void correctMemoryVisibility() throws InterruptedException {
        Thread withDelayedLock = new Thread(() -> {
            lock.lock();
            try {
                threadAcquired = "delayed";
                System.out.println("Acquired on delayed");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
 
        });
 
        lock.lock();
        try {
            withDelayedLock.start();
            Thread.sleep(500);
        } finally {
            lock.unlock();
        }
 
        while (true) {
            lock.lock();
            try {
                System.out.println("Currently acquired " + threadAcquired);
                if (threadAcquired.equals("delayed")) {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
 
        withDelayedLock.join();
    }

That’s all for now, we will later proceed on different type of locks and the Condition interface.

Source: javacodegeeks.com

Friday, October 14, 2022

Implement Interface using Abstract Class in Java

Java Interface, Abstract Class, Java Career, Java Prep, Java Preparation, Java Tutorial and Materials, Java Certification, Java Jobs

Interface contains only abstract methods that can’t be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can’t be instantiated and It is also possible for the class to have no methods at all. The instance of an abstract class can’t be created.

Now as all methods in an interface are abstract methods therefore we can implement it using Abstract Class.

1. Let’s create an Interface at first:


// creating an interface named ORACLEJAVACERTIFIED 
interface ORACLEJAVACERTIFIED { 
void learnCoding(); 
void learnProgrammingLanguage(); 
void contribute(); 
}

Here the three  non-implemented methods are the abstract methods

2. Now let’s implement the interface in an Abstract class named Student:


// creating an abstract class named Student which is 
// implementing the interface,ORACLEJAVACERTIFIED 
abstract class Student implements ORACLEJAVACERTIFIED { 
// Overriding two methods of the interfacem,ORACLEJAVACERTIFIED
@Override public void learnCoding() 
System.out.println( 
"Let's make coding a habit with ORACLEJAVACERTIFIED"); 
@Override public void learnProgrammingLanguage() 
System.out.println( 
"Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED"); 
}

Here we have overridden two abstract methods of the interface ORACLEJAVACERTIFIED.

3. Now let’s create a class JAVA which extends the abstract class, Student:


As previously mentioned, we can’t create an instance of our abstract class therefore we need to make a non-abstract class.

// creating an non-abstract class 
// JAVA which is extending Student 
class JAVA extends Student { 
// overriding the remaining method of the interface,ORACLEJAVACERTIFIED 
@Override public void contribute() 
System.out.println( 
"Now let's help others by contributing in ORACLEJAVACERTIFIED"); 
}

Here we have overridden the remaining method of the interface ORACLEJAVACERTIFIED.

Below is the overall implementation of the problem statement:

// Implemention of Interface using Abstract Class in Java 

// Interface ORACLEJAVACERTIFIED 
interface ORACLEJAVACERTIFIED { 
void learnCoding(); 
void learnProgrammingLanguage(); 
void contribute(); 

// Abstract class Student implementing from ORACLEJAVACERTIFIED interface 
abstract class Student implements ORACLEJAVACERTIFIED { 

// Overriding the methods 
@Override public void learnCoding() 
System.out.println( 
"Let's make coding a habit with ORACLEJAVACERTIFIED"); 
@Override public void learnProgrammingLanguage() 
System.out.println( 
"Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED"); 

// Extend the JAVA class by Student abstract class 
class JAVA extends Student { 
@Override public void contribute() 
System.out.println( 
"Now let's help others by contributing in ORACLEJAVACERTIFIED"); 

// Driver code 
public class Main { 
public static void main(String[] args) 
// New JAVA object is created 
JAVA oraclejavacertifiedStudent = new JAVA(); 

// Calls to the multiple functions 
oraclejavacertifiedStudent.learnCoding(); 
oraclejavacertifiedStudent.learnProgrammingLanguage(); 
oraclejavacertifiedStudent.contribute(); 
}

Output:


Let's make coding a habit with ORACLEJAVACERTIFIED
Let's master all fundamentals of java with the help of ORACLEJAVACERTIFIED
Now let's help others by contributing in ORACLEJAVACERTIFIED

Source: geeksforgeeks.org

Thursday, April 28, 2022

Bruce Eckel on Java interfaces and sealed classes

With the introduction of default and static methods in interfaces, Java lets you write method code in an interface that you might not want to be public.

With the introduction of default and static methods in interfaces, Java made it possible to write method code in an interface that you might not want to be public. In the code below, Old, fd(), and fs() are default and static methods, respectively. These methods are called only by f() and g(), so you can make them private.

Java Interfaces Classes, Oracle Java Sealed Classes, Oracle Java Exam Prep, Oracle Java Career, Java Skills, Oracle Java Preparation

// interfaces/PrivateInterfaceMethods.java

// {NewFeature} Since JDK 9

interface Old {

  default void fd() {

    System.out.println("Old::fd()");

  }

  static void fs() {

    System.out.println("Old::fs()");

  }

  default void f() {

    fd();

  }

  static void g() {

    fs();

  }

}

class ImplOld implements Old {}

interface JDK9 {

  private void fd() { // Automatically default

    System.out.println("JDK9::fd()");

  }

  private static void fs() {

    System.out.println("JDK9::fs()");

  }

  default void f() {

    fd();

  }

  static void g() {

    fs();

  }

}

class ImplJDK9 implements JDK9 {}

public class PrivateInterfaceMethods {

  public static void main(String[] args) {

    new ImplOld().f();

    Old.g();

    new ImplJDK9().f();

    JDK9.g();

  }

}

/* Output:

Old::fd()

Old::fs()

JDK9::fd()

JDK9::fs()

*/

(Note: The {NewFeature} comment tag excludes this example from the Gradle build that uses JDK 8.)

JDK9 turns fd() and fs() into private methods using the feature finalized in JDK 9. Note that fd() no longer needs the default keyword, as making it private automatically makes it default.

Sealed classes and interfaces

An enumeration creates a class that has only a fixed number of instances. JDK 17 finalizes the introduction of sealed classes and interfaces, so the base class or interface can constrain what classes can be derived from it. This allows you to model a fixed set of kinds of values.

// interfaces/Sealed.java

// {NewFeature} Since JDK 17

sealed class Base permits D1, D2 {}

final class D1 extends Base {}

final class D2 extends Base {}

// Illegal:

// final class D3 extends Base {}

The compiler produces an error if you try to inherit a subclass such as D3 that is not listed in the permits clause. In the code above, there can be no subclasses other than D1 and D2. Thus, you can ensure that any code you write will only ever need to consider D1 and D2.

You can also seal interfaces and abstract classes.

// interfaces/SealedInterface.java

// {NewFeature} Since JDK 17

sealed interface Ifc permits Imp1, Imp2 {}

final class Imp1 implements Ifc {}

final class Imp2 implements Ifc {}

sealed abstract class AC permits X {}

final class X extends AC {}

If all subclasses are defined in the same file, you don’t need the permits clause. In the following, the compiler will prevent any attempt to inherit a Shape outside of SameFile.java:

// interfaces/SameFile.java

// {NewFeature} Since JDK 17

sealed class Shape {}

final class Circle extends Shape {}

final class Triangle extends Shape {}

The permits clause allows you to define the subclasses in separate files, as follows:

// interfaces/SealedPets.java

// {NewFeature} Since JDK 17

sealed class Pet permits Dog, Cat {}

// interfaces/SealedDog.java

// {NewFeature} Since JDK 17

final class Dog extends Pet {}

// interfaces/SealedCat.java

// {NewFeature} Since JDK 17

final class Cat extends Pet {}

Subclasses of a sealed class must be modified by one of the following:

◉ final: No further subclasses are allowed.

◉ sealed: A sealed set of subclasses is allowed.

◉ non-sealed: This is a new keyword that allows inheritance by unknown subclasses.

The sealed subclasses maintain strict control of the hierarchy.

// interfaces/SealedSubclasses.java

// {NewFeature} Since JDK 17

sealed class Bottom permits Level1 {}

sealed class Level1 extends Bottom permits Level2 {}

sealed class Level2 extends Level1 permits Level3 {}

final class Level3 extends Level2 {}

Note that a sealed class must have at least one subclass.

A sealed base class cannot prevent the use of a non-sealed subclass, so you can always open things back up.

// interfaces/NonSealed.java

// {NewFeature} Since JDK 17

sealed class Super permits Sub1, Sub2 {}

final class Sub1 extends Super {}

non-sealed class Sub2 extends Super {}

class Any1 extends Sub2 {}

class Any2 extends Sub2 {}

Sub2 allows any number of subclasses, so it seems like it releases control of the types you can create. However, you strictly limit the immediate subclasses of the sealed class Super. That is, Super still allows only the direct subclasses Sub1 and Sub2.

A JDK 16 record (described in a previous article in this series) can also be used as a sealed implementation of an interface. Because a record is implicitly final, it does not need to be preceded by the final keyword.

// interfaces/SealedRecords.java

// {NewFeature} Since JDK 17

sealed interface Employee

  permits CLevel, Programmer {}

record CLevel(String type)

  implements Employee {}

record Programmer(String experience)

  implements Employee {}

The compiler prevents you from downcasting to illegal types from within a sealed hierarchy.

// interfaces/CheckedDowncast.java

// {NewFeature} Since JDK 1

sealed interface II permits JJ {}

final class JJ implements II {}

class Something {}

public class CheckedDowncast {

  public void f() {

    II i = new JJ();

    JJ j = (JJ)i;

    // Something s = (Something)i;

    // error: incompatible types: II cannot

    // be converted to Something

  }

}

You can discover the permitted subclasses at runtime using the getPermittedSubclasses() call, as follows:

// interfaces/PermittedSubclasses.java

// {NewFeature} Since JDK 17

sealed class Color permits Red, Green, Blue {}

final class Red extends Color {}

final class Green extends Color {}

final class Blue extends Color {}

public class PermittedSubclasses {

  public static void main(String[] args) {

    for(var p: Color.class.getPermittedSubclasses())

      System.out.println(p.getSimpleName());

  }

}

/* Output:

Red

Green

Blue

*/

Source: oracle.com

Monday, September 20, 2021

Differences between Interface and Class in Java

Java Interface, Java Class, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Java Preparation, Java Career

This article highlights the differences between a class and an interface in Java.

Class:

A class is a user-defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 

1. Modifiers: A class can be public or has default access.

2. Class name: The name should begin with a initial letter (capitalized by convention).

3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

5. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.

Example:

// Java program to demonstrate Class

// Class Declaration

public class Dog {

// Instance Variables

String name;

String breed;

int age;

String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

{

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

}

// method 1

public String getName()

{

return name;

}

// method 2

public String getBreed()

{

return breed;

}

// method 3

public int getAge()

{

return age;

}

// method 4

public String getColor()

{

return color;

}

@Override

public String toString()

{

return ("Hi my name is "

+ this.getName()

+ ".\nMy breed, age and color are "

+ this.getBreed() + ", "

+ this.getAge() + ", "

+ this.getColor());

}

public static void main(String[] args)

{

Dog tuffy = new Dog("tuffy", "papillon",

5, "white");

System.out.println(tuffy.toString());

}

}

Output: 

Hi my name is tuffy.
My breed, age and color are papillon, 5, white


Interface: 


Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body).   
 
◉ Interfaces specify what a class must do and not how. It is the blueprint of the class.

◉ An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.

◉ If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract.

◉ A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection.

Syntax : 

interface <interface_name> {
    
    // declare constant fields
    // declare methods that abstract 
    // by default.
}

Example: 

// Java program to demonstrate
// working of interface.

import java.io.*;

// A simple interface
interface in1 {

// public, static and final
final int a = 10;

// public and abstract
void display();
}

// A class that implements the interface.
class testClass implements in1 {

// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Oracle");
}

// Driver Code
public static void main(String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}

Differences between a Class and an Interface:


Class Interface 
The keyword used to create a class is “class” The keyword used to create an interface is “interface”
A class can be instantiated i.e, objects of a class can be created.  An Interface cannot be instantiated i.e, objects cannot be created. 
Classes does not support multiple inheritance.  Interface supports multiple inheritance. 
It can be inherit another class.  It cannot inherit a class. 
It can be inherited by another class using the keyword ‘extends’.  It can be inherited by a class by using the keyword ‘implements’ and it can be inherited by an interface using the keyword ‘extends’. 
It can contain constructors.  It cannot contain constructors. 
It cannot contain abstract methods.  It contains abstract methods only. 
Variables and methods in a class can be declared using any access specifier(public, private, default, protected)  All variables and methods in a interface are declared as public. 
Variables in a class can be static, final or neither.  All variables are static and final. 

Source: geeksforgeeks.org

Friday, August 20, 2021

Java 8 - Functional Interfaces

Java 8 - Functional Interfaces, Core Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Certification

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.

Functional Interface Example

Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false.

Create the following Java program using any editor of your choice in, say, C:\> JAVA.

Java8Tester.java

import java.util.Arrays;

import java.util.List;

import java.util.function.Predicate;

public class Java8Tester {

   public static void main(String args[]) {

      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

      // Predicate<Integer> predicate = n -> true

      // n is passed as parameter to test method of Predicate interface

      // test method will always return true no matter what value n has.

      System.out.println("Print all numbers:");

      //pass n as parameter

      eval(list, n->true);

      // Predicate<Integer> predicate1 = n -> n%2 == 0

      // n is passed as parameter to test method of Predicate interface

      // test method will return true if n%2 comes to be zero

      System.out.println("Print even numbers:");

      eval(list, n-> n%2 == 0 );

      // Predicate<Integer> predicate2 = n -> n > 3

      // n is passed as parameter to test method of Predicate interface

      // test method will return true if n is greater than 3.

      System.out.println("Print numbers greater than 3:");

      eval(list, n-> n > 3 );

   }

   public static void eval(List<Integer> list, Predicate<Integer> predicate) {

      for(Integer n: list) {

         if(predicate.test(n)) {

            System.out.println(n + " ");

         }

      }

   }

}

Here we've passed Predicate interface, which takes a single input and returns Boolean.

Verify the Result

Compile the class using javac compiler as follows −

C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows −

C:\JAVA>java Java8Tester

It should produce the following output −

Print all numbers:

1

2

3

4

5

6

7

8

9

Print even numbers:

2

4

6

8

Print numbers greater than 3:

4

5

6

7

8

9

Source: tutorialspoint.com

Friday, July 30, 2021

Interfaces and Polymorphism in Java

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs

Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts.

Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name.

Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading.

Types of polymorphism in Java:

1. Run time polymorphism

2. Compile-time polymorphism

Type 1: Run time polymorphism

This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing I/O classes

import java.io.*;

// Class 1 (Parent class)

class GFG1 {

//name method

void name() {

System.out.println("This is the GFG1 class");

}

}

// Class 2 (Chile class)

// Main class extending parent class

public class GFG extends GFG1 {

// Method 1

void name() {

// Print statement

System.out.println("This is the GFG class");

}

// Method 2

// Main drive method

public static void main(String[] args) {

// Now creating 2 objects with different references and

// calling the Method 1 over the objects

// Case 1: GFG1 reference and GFG1 is the object

GFG1 ob = new GFG1();

ob.name();

// Case 2: GFG1 reference and GFG is the object

GFG1 ob1 = new GFG();

ob1.name();

}

}

Output

This is the GFG1 class
This is the GFG class

Output explanation: 

In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism.

Type 2: Compile-time polymorphism

Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Helper class
class First {

// Method of this class
// Without any parameter
void check()
{

// Print statement if this method is called
System.out.println("This is the class First");
}
}

// Class 2
// Main class
class Second extends First {

// Method overloading
void check(String name)
{
// Printing the name of the class method having the
// parameter
System.out.println("This is the class " + name);
}

// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");

// Creating object of class 1
First ob1 = new First();
ob.check();

// Upcasting
First ob2 = new Second();
ob.check();
}
}

Output

This is the class Second
This is the class First
This is the class First

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs
Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java.

Real-life Example

The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees.

Example

// Java Program to Demonstarte Concept of interfaces

// Interfacce
interface salary {
void insertsalary(int salary);
}

// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

public class GFG {

public static void main(String[] args)
{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();

ob1.insertsalary(200000);
ob1.printSalary();
}
}

Output

100000
200000

Source: geeksforgeeks.org

Monday, April 19, 2021

Difference Between Package and Interface in Java

The key difference between Package and Interface in Java is that Package helps to categorize the classes methodically to access and maintain them easily while Interface helps to implement multiple inheritances and to achieve abstraction.

Java is one of the most popular programming languages. The main advantage of Java is that it supports Object Oriented Programming. This methodology allows modeling the real world objects in software. A class is a blueprint to create an object. Each object contains data or fields to describe the attributes or the properties and methods to describe behaviors. This article discusses two concepts related to OOP in Java  in Java that are Package and Interface.

What is Package in Java?

Java provides a large number of classes. Keeping all the classes in a single folder can be difficult because it is hard to access. This can affect the program manageability. Java uses packages to arrange classes. It is similar to a folder. Java API groups classes into different packages according to the functionality. Therefore, each package contains a related set of classes.

Example of Packages in Java

Few example packages are as follows. The java.io package contains the input, output supporting classes. It includes File, PrintStream, BufferInputStream etc. The java.net package contains the networking related classes. Some examples are URL, Socket, ServerSocket. The java.awt package contains all the classes required to build Graphical User Interfaces. Those are few Java API packages.

Read More: 1Z0-900: Java EE 7 Application Developer

When the programmer wants to use a certain class in the program, he should import that package. If the programmer wants to use the BufferInputStream class in the java.io package, he should write the import statement as follows.

import java.util.BufferInoutStream;

Below statement will import all the classes in the util package.

import java.util.*;

It is also possible to create user defined packages.

package employee;

public class Employee {

}

According to the above example, the employee is the package name. The Employee class is a part of the employee package. This file saves as Employee.java to the employee package.

Furthermore, it is possible to import a public class from one package to another. Refer the following example.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 01: Class A

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 02: Class B

Class A is in package 1, and it contains the public method called display. Class B is in package 2, and it contains the main method. Even though they are in separate packages; class B can create an object of class A by importing package1. After importing package 1, class B has access to the data and methods of class A.

Overall, Package in Java helps to organize the project files. This is very useful when developing large system because it allows storing all the files in methodical way.  In addition to that, the Java API packages allow the programmers to use already existing classes.

What is Interface in Java?


Sometimes the programmer might not know the definition of the method. In this situations, the programmer can only declare the method. An abstract method is a method that does not have a definition. It only has the declaration. When there is at least one abstract method, that class becomes an abstract class. Moreover, the abstract class can contain abstract methods as well as non-abstract methods. The programmer cannot create objects out of abstract classes.

When a class extends an abstract class, the new class should define all the abstract method in the abstract class. In other words, assume that abstract class A has an abstract method called display. Class B extends class A. Then class B should define the method display.

Example of Interface in Java


Assume that both A and B are abstract classes. If class C is extending A and B, that class C has to define the abstract methods of both classes. This is multiple inheritance. Java does not support multiple inheritance. To implement it, the programmer should use interfaces. If A and B are interfaces, then class C can implement them. Refer following example.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 03: Interface A

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 04: Interface B

The interface A has the display1 abstract method, and interface B has the display2 abstract method.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 05: Class C

Class C implements both A and B interfaces. Therefore, it should define both methods.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified
Figure 06: Main Method

Now in the main method, it is possible to create an object of C and call both methods. Likewise, interfaces help to implement multiple inheritance in Java.

Other than multiple inheritance, interfaces help to achieve abstraction. It is one major concept in OOP. Abstraction allows to hide the implementation details and show only the functionality to the user. Further, it allows focusing on what the object does instead of how it is done. As an interface consists of abstract methods, it helps to archive abstraction.

What is the Difference Between Package and Interface in Java?


Package is a group of related classes that provide access protection and namespace management. Interface is a reference type similar to class which is a collection of abstract methods. Package helps to categorize the classes methodically to access and maintain them easily. On the other hand, Interface helps to implement multiple inheritances and to achieve abstraction. This is the main difference between Package and Interface in Java. Further, the way to write a package is in lower case letters such as java.util, java.awt. If the name of the interface is Area, then it is written in, interface Area.

Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Career, Java Certified

Source: differencebetween.com

Friday, February 19, 2021

Difference between abstract class and interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Guides

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface 
Abstract class can have abstract and non-abstract methods.  Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Abstract class doesn't support multiple inheritance.  Interface supports multiple inheritance. 
Abstract class can have final, non-final, static and non-static variables.  Interface has only static and final variables. 
Abstract class can provide the implementation of interface.  Interface can't provide the implementation of abstract class. 
The abstract keyword is used to declare abstract class.  Interface can't provide the implementation of abstract class. 
An abstract class can extend another Java class and implement multiple Java interfaces.  An interface can extend another Java interface only. 
An abstract class can be extended using keyword "extends".  An interface can be implemented using keyword "implements". 
A Java abstract class can have class members like private, protected, etc.  Members of a Java interface are public by default. 
Example:
public abstract class Shape{
public abstract void draw();
Example:
public interface Drawable{
void draw();

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:

I am a
I am b
I am c
I am d

Wednesday, October 28, 2020

Comparator Interface in Java with Examples

Oracle Java Tutorial and Material, Java Certification, Oracle Java Exam Prep, Java Guides, Oracle Java Learning

Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following function compare obj1 with obj2

Syntax: 

public int compare(Object obj1, Object obj2):

Suppose we have an array/arraylist of our own class type, containing fields like rollno, name, address, DOB etc and we need to sort the array based on Roll no or name?

Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criterion like Roll No. and Name.

Method 2: Using comparator interface- Comparator interface is used to order the objects of user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using comparator, we can sort the elements based on data members. For instance it may be on rollno, name, age or anything else.

Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator. 

// To sort a given list. ComparatorClass must implement 

// Comparator interface.

public void sort(List list, ComparatorClass c)

How does Collections.Sort() work? 


Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0 or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for its sort.

Working Program:

// Java program to demonstrate working of Comparator 
// interface 
import java.util.*; 
import java.lang.*; 
import java.io.*; 

// A class to represent a student. 
class Student 
int rollno; 
String name, address; 

// Constructor 
public Student(int rollno, String name, 
String address) 
this.rollno = rollno; 
this.name = name; 
this.address = address; 

// Used to print student details in main() 
public String toString() 
return this.rollno + " " + this.name + 
" " + this.address; 

class Sortbyroll implements Comparator<Student> 
// Used for sorting in ascending order of 
// roll number 
public int compare(Student a, Student b) 
return a.rollno - b.rollno; 

class Sortbyname implements Comparator<Student> 
// Used for sorting in ascending order of 
// roll name 
public int compare(Student a, Student b) 
return a.name.compareTo(b.name); 

// Driver class 
class Main 
public static void main (String[] args) 
ArrayList<Student> ar = new ArrayList<Student>(); 
ar.add(new Student(111, "bbbb", "london")); 
ar.add(new Student(131, "aaaa", "nyc")); 
ar.add(new Student(121, "cccc", "jaipur")); 

System.out.println("Unsorted"); 
for (int i=0; i<ar.size(); i++) 
System.out.println(ar.get(i)); 

Collections.sort(ar, new Sortbyroll()); 

System.out.println("\nSorted by rollno"); 
for (int i=0; i<ar.size(); i++) 
System.out.println(ar.get(i)); 

Collections.sort(ar, new Sortbyname()); 

System.out.println("\nSorted by name"); 
for (int i=0; i<ar.size(); i++) 
System.out.println(ar.get(i)); 

Output: 

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipur

By changing the return value in inside compare method you can sort in any order you want. eg.for descending order just change the positions of a and b in above compare method.

Sort collection by more than one field:


Oracle Java Tutorial and Material, Java Certification, Oracle Java Exam Prep, Java Guides, Oracle Java Learning
We have discussed how to sort list of objects on the basis of single field using Comparable and Comparator interface But, what if we have a requirement to sort ArrayList objects in accordance with more than one fields like firstly sort, according to the student name and secondly sort according to student age.

Below is the implementation of above approach:

// Java program to demonstrate working of Comparator 
// interface more than one field 

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Comparator; 

class Student { 

// instance member variables 
String Name; 
int Age; 

// parameterized constructor 
public Student(String Name, Integer Age) { 
this.Name = Name; 
this.Age = Age; 

public String getName() { 
return Name; 

public void setName(String Name) { 
this.Name = Name; 

public Integer getAge() { 
return Age; 

public void setAge(Integer Age) { 
this.Age = Age; 

// overriding toString() method 
@Override
public String toString() { 
return "Customer{" + "Name=" + Name + ", Age=" + Age + '}'; 

static class CustomerSortingComparator implements Comparator<Student> { 

@Override
public int compare(Student customer1, Student customer2) { 

// for comparison 
int NameCompare = customer1.getName().compareTo(customer2.getName()); 
int AgeCompare = customer1.getAge().compareTo(customer2.getAge()); 

// 2-level comparison using if-else block 
if (NameCompare == 0) { 
return ((AgeCompare == 0) ? NameCompare : AgeCompare); 
} else { 
return NameCompare; 

public static void main(String[] args) { 

// create ArrayList to store Student 
List<Student> al = new ArrayList<>(); 

// create customer objects using constructor initialization 
Student obj1 = new Student("Ajay", 27); 
Student obj2 = new Student("Sneha", 23); 
Student obj3 = new Student("Simran", 37); 
Student obj4 = new Student("Ajay", 22); 
Student obj5 = new Student("Ajay", 29); 
Student obj6 = new Student("Sneha", 22); 

// add customer objects to ArrayList 
al.add(obj1); 
al.add(obj2); 
al.add(obj3); 
al.add(obj4); 
al.add(obj5); 
al.add(obj6); 

// before Sorting arraylist: iterate using Iterator 
Iterator<Student> custIterator = al.iterator(); 

System.out.println("Before Sorting:\n"); 
while (custIterator.hasNext()) { 
System.out.println(custIterator.next()); 

// sorting using Collections.sort(al, comparator); 
Collections.sort(al, new CustomerSortingComparator()); 

// after Sorting arraylist: iterate using enhanced for-loop 
System.out.println("\n\nAfter Sorting:\n"); 
for (Student customer : al) { 
System.out.println(customer); 

Output:

Before Sorting:

Customer{Name=Ajay, Age=27}
Customer{Name=Sneha, Age=23}
Customer{Name=Simran, Age=37}
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=29}
Customer{Name=Sneha, Age=22}

After Sorting:

Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}

Monday, October 5, 2020

Difference between Abstract Class and Interface in Java

Prerequisite

Interface

An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).

Abstract Class

Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

Abstraction: Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.

Abstract class vs Interface

1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.

2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.

3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.

4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.

5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.

6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.

7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

// Java program to illustrate the 
// concept of abstract class 

import java.io.*; 

// abstract class 
abstract class Shape 
// declare fields 
String objectName = " "; 
Shape(String name) 
this.objectName = name; 
// declare non-abstract methods 
// it has default implementation 
public void moveTo(int x, int y) 
System.out.println(this.objectName + " " + "has been moved to"
+ " x = " + x + " and y = " + y); 
// abstract methods which will be 
// implemented by its subclass(es) 
abstract public double area(); 
abstract public void draw(); 

class Rectangle extends Shape 
int length, width; 
// constructor 
Rectangle(int length, int width, String name) 
super(name); 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle extends Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius, String name) 
super(name); 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape class reference. 
Shape rect = new Rectangle(2,3, "Rectangle"); 
System.out.println("Area of rectangle: " + rect.area()); 
rect.moveTo(1,2); 
System.out.println(" "); 
// creating the Objects of circle class 
Shape circle = new Circle(2, "Cicle"); 
System.out.println("Area of circle: " + circle.area()); 
circle.moveTo(2,4); 

Output:

Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2
 
Area of circle: 6.28
Cicle has been moved to x = 2 and y = 4

In you don’t have any common code between rectangle and circle then go with interface.

// Java program to illustrate the 
// concept of interface 
import java.io.*; 

interface Shape 
// abstract method 
void draw(); 
double area(); 

class Rectangle implements Shape 
int length, width; 
// constructor 
Rectangle(int length, int width) 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle implements Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius) 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape interface reference. 
Shape rect = new Rectangle(2,3); 
System.out.println("Area of rectangle: " + rect.area()); 

// creating the Objects of circle class 
Shape circle = new Circle(2); 
System.out.println("Area of circle: " + circle.area()); 

output

Area of rectangle: 6.0
Area of circle: 6.28

When to use what?


Consider using abstract classes if any of these statements apply to your situation:

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

  • In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
  • You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
  • You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:

  • It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
  • A class can implement more than one interface. It is called multiple inheritance.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.