Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

Java 101Using an interface as a parameter

time to read 1 min | 151 words

You can define methods that take an interface as a parameter. Your interface defines a contract and your methods will accept as parameter any objects whose class implements that interface. This is in fact one of the most common and useful ways to use an interface.

interface Test {
  public void test(); //define the interface
}

class Tester {
  public void runTest(Test t) {
    t.test(); 
  } // method with interface as param
}

MyTest class will implement this interface:

class MyTest implements Test {
  public void test() { // running code }
}

Now the runTest method will take as a parameter any object that implements the Test Interface:

Tester tester = new Tester(); Test test1 = new MyTest(); tester.runTest(test1);

The collection framework from the standard Java API frequently uses this procedure. For example, Collections.sort() can sort any class that implements the List interface and whose contents implement the Comparable interface.

Java 101Using bounded type parameters in generic methods

time to read 1 min | 114 words

Sometimes it may be appropriate to write a generic method, however it will not be possible for it to accept every type while still maintaining all the necessary functionality.

To solve this, use bounded type parameters to restrict generic methods from accepting arguments of a particular kind.

public <T extends Shape> 
  void drawAll(List<T> shapes){
    for (Shape s: shapes) {
        s.draw(this);
    }
}

The above method is used to draw a list of shapes. Writing a generic method with an unbounded type parameter would cause problems because lists of other types cannot be drawn in this way.

By specifying that <T extends Shape> we guarantee that only Shape objects can be passed to the method.

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha