JavaRush/Java Blog/Random EN/Coffee break #133. How to get only part of an array in Ja...

Coffee break #133. How to get only part of an array in Java. Interfaces and Abstract Classes in Java

Published in the Random EN group
members

How to get only part of an array in Java

Source: Asyncq Copying part of an array is a very common operation that every developer encounters. In this article, we will see traditional imperative style and modern declarative style code with lambda expression and streaming API. Coffee break #133.  How to get only part of an array in Java.  Interfaces and abstract classes in Java - 1

Imperative approach

The imperative programming style has long been common in Java. Therefore, it is natural for Java developers to write the below code to copy a specific part of the original array. To do this, simply iterate through the elements, filtering out only those that are needed, and write them into the final array.

 private static int[] copyArray(){
        int[] numbers = {1,2,3,4,5,6,7};
        int[] subArray = new int[numbers.length-3];
        int j =3;
        for (int i=0;i<subArray.length;i++){
            subArray[i] = numbers[j+i];
        }
        System.out.println(Arrays.toString(subArray));
        return subArray;
    }
Many of us often forget that the Java Arrays library has a convenient copyOfRange method . This method can be used to copy part of an array by passing to and from the index.

private static int[] copyArray1(){
  int[] numbers = {1,2,3,4,5,6,7};
  int[] subArray = Arrays.copyOfRange(numbers,3,numbers.length);
  System.out.println(Arrays.toString(subArray));
  return subArray;
}

Declarative approach

Since Java 8 we can use the Streams API to copy part of an array. In the code below, we can pass int[] and filter out only values ​​greater than 3 and finally copy them into an array.

private static void copyArray2(){
        int[] numbers = {1,2,3,4,5,6,7};
        // copy with values
        int[] subArray = Arrays.stream(numbers).filter(a-> a>3).toArray();
        System.out.println(Arrays.toString(subArray));
    }
The above code is a value-based copy of a portion of the array, but we can also copy based on an index. Below the code we broadcast Intstream from i=0; i=len(array) . Typically in imperative code we write a for loop from the start index to the end index and iterate over each element. We can do the same thing using Intstream and access the index element .

// copy with index
int[] subArray1 = IntStream
                .range(0, numbers.length)
                .filter(i -> i > 3)
                .map(a->numbers[a]).toArray();

System.out.println(Arrays.toString(subArray1));
While the above method works, we have another way in which we can use AtomicInteger to copy part of the array. It has a getAndIncrement method which essentially provides an index and increments it by 1.

// copy with index
AtomicInteger atomicInteger = new AtomicInteger();
int[] subArray2 = Arrays.stream(numbers).filter(i -> atomicInteger.getAndIncrement() > 3).toArray();
System.out.println(Arrays.toString(subArray2));

Conclusion

In this article, we have discussed how you can copy part of a Java array using imperative and declarative styles. I would prefer to work in a declarative style as it makes my code more readable and less verbose.

Interfaces and Abstract Classes in Java

Source: Devgenius When learning the Java language, we certainly come across a concept called Interfaces. Interfaces are one of the key features of Java, so every developer should know how to use them. It is important to remember that interfaces have both their advantages and disadvantages. Let's dive deeper into understanding interfaces. When implementing interfaces, we encounter abstract classes. What are abstract classes? What are they needed for? What is an interface? How are they used? Why do interfaces use abstract classes? You will get answers to all these questions in this article. Coffee break #133.  How to get only part of an array in Java.  Interfaces and Abstract Classes in Java - 2

What is an interface?

An interface is a special mechanism in Java that describes behavior and helps achieve abstraction. It is similar to a class in many ways because it has static constants and abstract methods. Interfaces can only have abstract methods (methods without a body). Brief difference between interface and abstract class:
  • The interface does not have any methods implemented; they are all public and there are no class variables.
  • An abstract class is a class that does not have one or more methods implemented.
Since Java 9, we can also use private , default , and static methods in interfaces . Now let's move on to the simple interface logic that is used to achieve the abstraction.

What is abstraction?

Let's take a real life example. We all use apps on our mobile phones. Whenever we want to use any application, we have to create an account in it. When we register through our phone number, a one-time password is sent to our mobile phone. We know that the password is received after clicking the “Get Password” button in the application, but we do not know how this system works in the backend and what actually happens after clicking the button. Now, the process of successfully completing tasks without showing the user what is actually happening in the backend is known as abstraction. In Java, we can achieve abstraction using interfaces and abstract classes.

Why use the interface?

There are three reasons to use the interface:
  • To achieve abstraction.
  • To support multiple inheritance functionality.
  • To achieve loose coupling.

How to use the interface?

An interface is declared using the interface keyword . It provides abstraction, that is, it declares the structure of the class. All methods in an interface are abstract and are set to public, static, and final by default ( public , static , final ). Whatever class implements an interface must implement all the methods declared in the interface.

interface <interface_name>{  
       
     // declare constant fields  
     // declare methods that abstract   
     // by default. 
 }
Similar to interface abstraction, abstraction can also be achieved using abstract classes.

What are abstract classes?

Abstract classes are classes with the abstract keyword in front of them. They contain both abstract and concrete methods (with a body). Abstract classes cannot be instantiated, they must be extended and their methods must be implemented. An abstract class describes some abstract object (car, person, etc.), not just behavior. Remember:
  • An abstract class must be declared with the abstract keyword .
  • There can be abstract and non-abstract methods.
  • An instance of an abstract class cannot be created.
  • It can have constructors and static methods.
  • It can have final methods that will force the subclass not to change the method body.
Example of an abstract class with an abstract method: In this example , Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class .

abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}
Abstract class having a constructor, data member and methods: An abstract class can have a data member, abstract method, method body (non-abstract method), constructor and even a main() method .

//Example of an abstract class that has abstract and non-abstract methods  
 abstract class Bike{  
   Bike(){System.out.println("bike is created");}  
   abstract void run();  
   void changeGear(){System.out.println("gear changed");}  
 }  
//Creating a Child class which inherits Abstract class  
 class Honda extends Bike{  
 void run(){System.out.println("running safely..");}  
 }  
//Creating a Test class which calls abstract and non-abstract methods  
 class TestAbstraction2{  
 public static void main(String args[]){  
  Bike obj = new Honda();  
  obj.run();  
  obj.changeGear();
}
}
Now the main question arises. If interfaces and abstract classes help with abstraction, which one is better to use? The answer is that Java does not support multiple inheritance like C++ does. That is, if we need to achieve multiple inheritance, then we should use interfaces. In other words, abstract classes help from 1 to 100% of cases, and interfaces help in 100% of cases. If we need behavior, we need to use an interface. If we are talking about a conceptual object, we must use an abstract class.

Java Interface Example

In this example, the Drawable interface has only one method. Its implementation is provided by the Rectangle and Circle classes . In a real scenario, the interface is defined by someone else and its implementation is provided by different implementation providers. Moreover, it is being used by someone else. Part of the implementation is hidden by the user using the interface.

//Interface declaration: by first user  
interface Drawable{  
void draw();  
}  
//Implementation: by second user  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
class Circle implements Drawable{  
public void draw(){System.out.println("drawing circle");}  
}  
//Using interface: by third user  
class TestInterface1{  
public static void main(String args[]){  
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()  
d.draw();  
}}

Multiple Inheritance in Java Using Interface

If a class implements multiple interfaces or an interface extends multiple interfaces, it is called multiple inheritance.

interface Printable{  
void print();  
}  
interface Showable{  
void show();  
}  
class A7 implements Printable,Showable{  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}
Question: Multiple inheritance is not supported through a class in Java, but it is possible through an interface, why? As already explained in the section on inheritance, multiple inheritance is not supported in the class example due to ambiguity. However, it is supported by the interface example because there is no ambiguity in it. The reason is that its implementation is provided by the implementation class.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet