Monday, July 9, 2018

Java Generics and the Anonymous Class

Interfaces can not be instantiated since interface methods do not have 
implemented methods, but methods can be implemented when the constructor is 
called. This can be done with generics as well, so keep practicing. 
 
public class HelloGeneric {
        public static void main(String[] args) {
  anonMethod();
 }
 
 public static void anonMethod() {
  // create a generic class with default access modifier and implement the 
                // interface
  class MyClass<T> implements HelloI<T> {
       public void printMsg(T m) {
           System.out.println(m + ".) Hello from anonymous class. ");
       }
  }
  MyClass<Integer> mc = new MyClass<Integer>();
  mc.printMsg(1);
 
  // implement methods in order to instantiate an interface without 
                // a separate implementing class
  HelloI<String> mc2 = new HelloI<String>() {
            public void printMsg(String m) {
       System.out.println(m + ".) Hello from another anonymous class. ");
     }
  };
  mc2.printMsg("Testing");
 }
}
 
Do not over complicate while you practice these concepts.  Just keep the code simple.
 
//generic interface to implement
public interface HelloI<T>
{
 public void printMsg(T m);
}

These anonymous classes show up as inner classes with an index value attached to them. 

1 comment:

  1. Very impressive article! The blog is highly informative and has answered all my questions. To introduce about our company and the activities, Pegasi Media Group is a database provider that helps you to boost your sales & grow your business through well-build Java user list

    ReplyDelete