Hi I'm just learning how to use abstract classes and interfaces. The code below is intended to be used by other classes to sort arrays in a number of different ways.
import java.util.Random;
public interface ArraySort {
// sorts the array using insertion sort
public default int[] sortInsertion(int[] array){
int j; // the number of items sorted so far
int key; // the item to be inserted
int i;
for (j = 1; j < array.length; j++) // Start with 1 (not 0)
{
key = array[ j ];
for(i = j - 1; (i >= 0) && (array[ i ] < key); i--) // Smaller values are moving up
{
array[ i+1 ] = array[ i ];
}
array[ i+1 ] = key; // Put the key in its proper location
}
return array;
}
// shuffles the array
public default int[] shuffle(int[] array){
Random rgen = new Random(); // Random number generator
for (int i=0; i<array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
// prints the array elements
public default void print(int[] array){
System.out.println(array);
}
// initialize array from firstElement to lastElement
public int[] init(int firstElement, int lastElement);
}
I would like to know if this is necessarily an appropriate implementation of an abstract interface. Is there something that would make it much more efficient? Is there a better way to be doing this? What I want to know specifically is whether or not my code is 100% faithful to the concept of abstract classes and interfaces because I'm just trying to learn it in the best way possible.
Interfaces define methods without implementation. A class will then implement the interface and provide the method body.
Abstract classes cannot be instantiated, but they can be subclassed.
Here is a Java tutorial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.