Java generics inheritance

One o'clock eye

After creating an interface with a generic statement, the parent class to subclass from the parent class can implement this interface to create a class, or, it is worth noting that, when using these interfaces, the parent class can no longer contain the type of parameter.

If you do not pass the actual type parameters when using a generic class, Java compiler might issue a warning: the use of unchecked or unsafe operations - this is a generic check warning.

Two combat - the actual type arguments passed in

public class A1 extends Apple<String> {
    // 正确重写了父类的方法,返回值
    // 与父类Apple<String>的返回值完全相同
    public String getInfo() {
        return "子类" + super.getInfo();
    }
   /*
   // 下面方法是错误的,重写父类方法时返回值类型不一致
   public Object getInfo()
   {
      return "子类";
   }
   */
}

Three combat - the actual type parameter is not passed

public class A2 extends Apple {
    // 重写父类的方法
    public String getInfo() {
        // super.getInfo()方法返回值是Object类型,
        // 所以加toString()才返回String类型
        return super.getInfo().toString();
    }
}

Four generic class does not exist

1:00 eye

  • Although the ArrayList <String> class as a subclass of ArrayList, in fact ArrayList <String> class indeed is a special class ArrayList, the ArrayList <String> object can only add String objects as a collection of elements. But in fact, the system does not generate a new class file as ArrayList <String>, and nor will ArrayList <String> as a new class to handle.

  • In fact, its all possible generic type parameters, have the same behavior, which can be the same class as many different classes to handle. This is exactly the same, static class variables and methods are shared among all instances, it is in a static method, a static initializer, or the static variables declared and initialized type parameter is not allowed.

  • The system does not actually generate a generic class, generic class can not be used after instanceof operator.

2 combat

public class R<T>
{
   // 下面代码错误,不能在静态变量声明中使用类型形参
// static T info;
   T age;
   public void foo(T msg){}
   // 下面代码错误,不能在静态方法声明中使用类型形参
// public static void bar(T msg){}

}

 

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/93784080
Recommended