Generics in constructor of subclass?

I have a trivial bit of code that won't compile and I think it's a generic problem. I am rusty, though, so if I've made a basic Java mistake I do apologise.
I want to work with a subclass of the SoftReference class, but my use of the super() method gives a compiler error.
Here's the code:
import java.lang.ref.SoftReference;
import java.lang.ref.ReferenceQueue;
public class Tsoft<K> {
    ReferenceQueue<K>   rq;
    private class SoftItem<K> extends SoftReference<K> {
        public SoftItem (K key) {
            super (key, rq);
    }And running javac with -Xlint:unchecked gives this error message:
Tsoft.java:9: cannot find symbol
symbol  : constructor SoftReference(K,java.lang.ref.ReferenceQueue<K>)
location: class java.lang.ref.SoftReference<K>
                        super (key, rq);
                        ^
1 errorI'm running Java(TM) SE Runtime Environment (build 1.6.0_10-b33).
Thanks for any help anyone can offer!

You introduced a "new" K parameter in SoftItem. This will compile:
import java.lang.ref.SoftReference;
import java.lang.ref.ReferenceQueue;
public class Tsoft<K> {
    ReferenceQueue<? super K> rq;
    private class SoftItem extends SoftReference<K> {
     public SoftItem(K key) {
         super(key, rq);
}Piet

Similar Messages

  • Why can't classes with private constructors be subclassed?

    Why can't classes with private constructors be subclassed?
    I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
    Example:
    I really, really want to be able to subclass java.util.Arrays, like so:
    package com.tassajara.util;
    import java.util.LinkedList;
    import java.util.List;
    public class Arrays extends java.util.Arrays {
        public static List asList(boolean[] array) {
            List result = new LinkedList();
            for (int i = 0; i < array.length; i++)
                result.add(new Boolean(array));
    return result;
    public static List asList( char[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Character(array[i]));
    return result;
    public static List asList( byte[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Byte(array[i]));
    return result;
    public static List asList( short[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Short(array[i]));
    return result;
    public static List asList( int[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Integer(array[i]));
    return result;
    public static List asList( long[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Long(array[i]));
    return result;
    public static List asList( float[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Float(array[i]));
    return result;
    public static List asList( double[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Double(array[i]));
    return result;
    // Now that we extend java.util.Arrays this method is not needed.
    // /**JCF already does this so just wrap their implementation
    // public static List asList(Object[] array) {
    // return java.util.Arrays.asList(array);
    public static List asList(Object object) {
    List result;
    Class type = object.getClass().getComponentType();
    if (type != null && type.isPrimitive()) {
    if (type == Boolean.TYPE)
    result = asList((boolean[])object);
    else if (type == Character.TYPE)
    result = asList(( char[])object);
    else if (type == Byte.TYPE)
    result = asList(( byte[])object);
    else if (type == Short.TYPE)
    result = asList(( short[])object);
    else if (type == Integer.TYPE)
    result = asList(( int[])object);
    else if (type == Long.TYPE)
    result = asList(( long[])object);
    else if (type == Float.TYPE)
    result = asList(( float[])object);
    else if (type == Double.TYPE)
    result = asList(( double[])object);
    } else {
    result = java.util.Arrays.asList((Object[])object);
    return result;
    I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.

    Why can't classes with private constructors be
    subclassed?Because the subclass can't access the superclass constructor.
    I really, really want to be able to subclass
    java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
    I do not intend to instantiate
    com.tassajara.util.Arrays as all my methods are static
    just like java.util.Arrays. You can see where I
    started to wrap asList(Object[] o). I could continue
    and wrap all of java.util.Arrays methods, but thats
    annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
    It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
    Precisely as you said, if they didn't want me to
    subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
    But they didn't. There has to be a way for an API
    developer to indicate that a class is merely not to be
    instantiated, and not both uninstantiable and
    unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays

  • NullPointer inside constructor for Subclass, but not for Superclass.

    Here is my Character class:
    public class Human extends Animal
      public Human(String name)
        super(name);
      public String toString()
         return "A human named: " + getName();
    }Here is my Animal class:
    public class Animal
       private String name;
       public Animal(String name)
          this.name = name;
          System.out.println(this);
       public String getName()
          return name;
       public String toString()
          return "An animal named: " + getName();
    }When I type:
    Human h = new Human("Bob");I get a null pointer exception. It should print: "A human named Bob".
    But if I type:
    Animal a = new Animal("Monkey");It prints: "An animal named Monkey" (no null pointer exception).
    So what is wrong with my code? I figure it has something to do with "this" not being ready since the constructor has not finished. Accordingly to that logic, Monkey shouldn't have worked either. Maybe there is something I don't know about Java. Anyway, what is the source of my problem?

    woipy,
    EDIT: Deleted BAD Advice.... sorry....
    this works for me.... so I'm failing to reproduce the error... can't reproduce it, can't fix it.
    package forums;
    class Human extends Animal
      public Human(String name) {
        super(name);
      public String toString() {
         return "A human named: " + getName();
    class Animal
       private String name;
       public Animal(String name) {
          this.name = name;
          System.out.println(this);
       public String getName() {
          return name;
       public String toString() {
          return "An animal named: " + getName();
    public class InheritanceContructorTest
      public static void main(String[] args) {
        try {
          Animal a = new Animal("Rover");
          Animal ah = new Human("Bob");
          Human h = new Human("Sue");
        } catch (Exception e) {
          e.printStackTrace();
    output
    An animal named: Rover
    A human named: Bob
    A human named: SueCheers. Keith.
    Edited by: corlettk on 20/09/2009 10:16

  • Using super class constructor in subclass constructor

    Hi all. How can I use Person() in my Client()?
    something like this:
    public class Client extends Person{
          private float balance;
          Client(String firstName,String midleName,String lastName,Contacts contacts,Adress adress,float balance){
               this= Person(firstName,midleName,lastName,contacts,adress);
               this.balance=balance;
          }

    public class Client extends Person{
      private float balance; // float?!? Are you sure.... ?
      Client(String firstName,String midleName,String lastName,Contacts contacts,Adress adress,float balance){
        super(firstName,midleName,lastName,contacts,adress);
        this.balance=balance;
    }

  • Downcasting a subclass of a concrete generic

    Hi--
    Been puzzling over this one for quite awhile, and I still can't figure it out. I'm trying to downcast a generic type to a subclass of a concrete type. Now admittedly that's messy and I'd like to refactor, but I'm still puzzled. Take the following code:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2("hello");
         System.err.println("Calling a method: " + ((Test2) testObj)).aMethod());
    public class Test2 extends Test1<String> {
        public Test2(String obj) {
         super(obj);
        public String aMethod() {
         return obj;
    }This fails to compile, saying that Test1<capture of ?> isn't convertible to Test2.
    Now suppose I change to the following:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2<String>("hello");
         System.err.println("Calling a method: " + ((Test2) testObj).anotherMethod());
    public class Test2<T extends String> extends Test1<T> {
        public Test2(T obj) {
         super(obj);
        public String anotherMethod() {
         return obj;
    }Here all I've done is add a parameter to the Test2 type that gives the same information available in item 1. In this case, however, it compiles and runs fine.
    Even more oddly, the following also works and does not produce any warnings:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2("hello");
         System.err.println("Calling a method: " + ((Test2) ((Test1) testObj)).anotherMethod());
    public class Test2 extends Test1<String> {
        public Test2(String obj) {
         super(obj);
        public String anotherMethod() {
         return obj;
    }So essentially the system is ok as long as I cast the generic type to a raw type, and then downcast to the subclass of the concrete type... but I can't do the cast directly?
    My feeling is that Java is being a little overly touchy about trying to prevent casting to a concrete type-- in the case where the type you're trying to cast to is itself not generic, shouldn't that be allowed? Or am I missing something subtle about how the generics work?

    Correct me if I'm wrong, but I think this may be your problem:
    public class Test2 extends Test1<String> {
    }This means that Test2 is a subclass of Test1<String> -- not Test1<?>. Here's why.
    If we "expand out," say, Test1<Integer> and Test1<String>, we get the following:
    public class Test1String {
       protected final String obj;
       public Test1String(String obj) {
       this.obj = obj;
    public class Test1Integer{
       protected final Integer obj;
       public Test1Integer(Integer obj) {
       this.obj = obj;
    }Now, it's easy to see that inheriting from each of these classes yields completely different results. Once you've parameterized a class, it becomes a completely different beast. Sooo, saying that
    Test1<?> testObj = new Test2("hello");could be the same thing as saying (since ? means any parameter), in our expanded form,
    Test1Integer testObj = new Test2("hello"); //aka, a new Test1String
    //or Test1Object, Test1MyComplicatedType, whateverwhich is clearly not allowed, since all the fields would be of a completely different type.
    I hope this helps!

  • Is it possible to override super class constructor?

    Is it possible to override super class constructor form subclass?

    However, you can achieve do something that looks similar to overriding.
    class Parent {
      Parent(int i, String s) {
        // do stuff
    class Child extends Parent {
      Child(int i, String s) {
        super(i, s);
        // do Child stuff here
    new Parent(1, "abc");
    new Child(2, "xyz");Although that's not overriding, it sort of looks similar. Is this what you were talking about?

  • Create an object instance without calling its constructor?

    Hi,
    Sometimes it's useful to create object instances without calling their constructor. When? For example object deserialization.
    By default when deserializating an object, the instance in the VM is created by calling the default constructor of the first non Serializable super-class (if you don't have such you're in trouble). I think that the db4o object database don't even call any constructor you may have written.
    So such thing exists, but how is this possible? I fugured out that sun's deserialization mechanism first finds the constructor of the first non Serializable super-class and then:
    cons = reflFactory.newConstructorForSerialization(cl, cons); Here I'm stuck.
    Here's the source of the method for finding serializable constructor:
         * Returns subclass-accessible no-arg constructor of first non-serializable
         * superclass, or null if none found.  Access checks are disabled on the
         * returned constructor (if any).
        private static Constructor getSerializableConstructor(Class cl) {
         Class initCl = cl;
         while (Serializable.class.isAssignableFrom(initCl)) {
             if ((initCl = initCl.getSuperclass()) == null) {
              return null;
         try {
             Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
             int mods = cons.getModifiers();
             if ((mods & Modifier.PRIVATE) != 0 ||
              ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
               !packageEquals(cl, initCl)))
              return null;
             cons = reflFactory.newConstructorForSerialization(cl, cons);
             cons.setAccessible(true);
             return cons;
         } catch (NoSuchMethodException ex) {
             return null;
        }So any info about this ReflectionFactory, and the problem as a whole?
    Thanks.

    So the question is how to create object instance without initializing it (calling the constructor)? And if you have any info about ReflectionFactory it will be useful too.
    When serializing an object you save all its fields and some extra info. When you deserialize it you have to reconstruct it, by copying the fields back, but not to reinitialize.
    import java.lang.reflect.*;
    import java.io.Serializable;
    import java.security.AccessController;
    import sun.reflect.ReflectionFactory;
    public class Test0 implements Serializable {
        public Test0() {
            System.out.println("Test0");
        public static void main(String[] args) throws Exception {
            Constructor<Test0> constr = reflectionFactory.newConstructorForSerialization(Test0.class, Object.class.getConstructor(new Class[0]));
            System.out.println(constr.newInstance(new Object[0]).getClass());
        private static final ReflectionFactory reflectionFactory = (ReflectionFactory)
         AccessController.doPrivileged(
             new ReflectionFactory.GetReflectionFactoryAction());
    }When you execute this piece you get:
    class Test0

  • Execution of class_constructors in subclass

    hi all, i'm new to abap objects but the testing the code below puzzles me.  can anyone explain why if i execute WRITE b=>d, the sub class_constructor is not executed?  i would expect that after executing the super c-c, the sub c-c is next.  as expected, only the super c-c is executed for WRITE a=>d.
    i had read, once a subclass is addressed, the c-c is executed if it hasn't been yet, after all unperformed super c-c's are executed.  but why when addressing b=>d not perform it?
    CLASS a DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA d TYPE c VALUE 'D'.
        CLASS-METHODS class_constructor.
    ENDCLASS.
    CLASS b DEFINITION INHERITING FROM a.
      PUBLIC SECTION.
        CLASS-METHODS class_constructor..
    ENDCLASS.
    CLASS a IMPLEMENTATION.
      METHOD class_constructor.
        WRITE:/ 'Superclass constructor'.
      ENDMETHOD.
    ENDCLASS.
    CLASS b IMPLEMENTATION.
      METHOD class_constructor.
        WRITE:/ 'Subclass constructor'.
      ENDMETHOD.
    ENDCLASS.

    Hi,
    b=>d  is a static component. There is no need to instantiante a class b (= calling the constructor) and this means that the class to the class_constructor is deferred as well. The only thing which is for shure is that the class_constructor of B is called before the constructor of B. But up to now this is not necessary.
    If you do the following the class_constructor of B is called.
    report  zzztest.
    class a definition.
      public section.
        class-data d type c value 'D'.
        class-methods class_constructor.
        methods constructor.
    endclass.                    "a DEFINITION
    class b definition inheriting from a.
      public section.
        class-methods class_constructor.
        methods constructor.
    endclass.                    "b DEFINITION
    class a implementation.
      method class_constructor.
        write:/ 'Superclass class constructor'.
      endmethod.                    "class_constructor
      method constructor.
        write:/ 'Superclass constructor'.
      endmethod.                    "class_constructor
    endclass.                    "a IMPLEMENTATION
    class b implementation.
      method class_constructor.
        write:/ 'Subclass class constructor'.
      endmethod.                    "class_constructor
      method constructor.
        super->constructor( ).
        write:/ 'Subclass constructor'.
      endmethod.                    "class_constructor
    endclass.                    "b IMPLEMENTATION
    data l_b type ref to b.
    end-of-selection.
      write / 'Start'.
      create object l_b.
      write / b=>d.
    The output is:
    Superclass class constructor
    Start
    Subclass class constructor
    Superclass constructor
    Subclass constructor
    D
    End
    Please be aware the a class_constructor is only called once for each class. The constructor is called for each object.
    Hope this helps.
    Regards Matthias

  • Superclass and subclass

    Ok I have now reached the area of using Superclass and subclass in my
    self study of Java, and I am stumped on what is I am sure is a very
    easy concept. Here's the Scenerio. I have three classes Point, Circle
    and InheritanceTest. Point is the Superclass that is being referenced
    from Circle InheritanceTest has the main Method.
    Inside the Point class the book I am using has this note inside the
    constructor.
    public void Point{
    //implicit call to superclass constructor occurs here
    setPoint(0,0);
    My question is this, Is the call to it's self or the object class?
    And do you Know which one it is referring to?
    Thanks in advance

    public void Point{
    //implicit call to superclass constructor occurs here
    setPoint(0,0);
    }When you extend a class, every constructor of the new class must call a constructor of the extended class- this is done by using super() or super(some arguments). Note that if you don't put this in, java will implicitly call super() for you- it basically inserts this call into your new constructor.
    As for the setPoint() method, if your new class has a method of this name and signature (i.e. same type of arguments), it will call your sub-class's method. If the sub-class does not have a method like this defined, it will look for this method in the super-class and call that one. In this way, you are inheriting the methods of the super-class. Unless you specifically override a method (give a method of the same name in type in the sub-class as in the super-class), all public or protected methods of the super-class can be used as if they were methods of your sub-class.
    Check this out:
    public class SuperClass
         private int value = 0;
         public SuperClass()
              super();
              // Calling the default constructor of Object, the superclass of this class
         public SuperClass(int value)
              // Implicitly calling super() since a superclass constructor was not given explicitly
              this.value = value;
         public int getValue()
              return value;
         public void setValue(int value)
         this.value = value;
         public void changeValue()
              setValue(getValue() + 1);
    public class SubClass
         public SubClass()
              super(0);     // Calls the SuperClass(int) constructor
         public SubClass(int value)
              // Implicit call to SuperClass() constructor
              setValue(value);
         public void changeValue()
              // Overrides the SuperClass method of the same name
              setValue(getValue() - 1);
         public void useSuperChangeValue()
              super.changeValue();     // Calls SuperClass.changeValue()
         // If you want to use the super-class methods, even if they have been overridden,
         // use the keyword "super" to reference the superclass

  • Overriding constructors with static parameters?

    I have an abstract class named Stuk with the following constructor:
         public Stuk(boolean rdstuk, String soort){
              roodstuk = rdstuk;
         }and i have a couple of subclasses like this one:
    public Maarschalk(boolean rdstuk, soort){
              super(rdstuk, "maarschalk");
         }with soort being a static string that differs in every subclass
    i tried this because i want to be able to make an object of a certain subclass without making if-else constructions to make sure the proper constructor is used.
    ofcourse, the static variable method doesnt work
    any other suggestions?
    thanks in advance

    oh sorry i misposted the constructors
    code of the constructor of abstract class Stuk:
    public abstract class Stuk{
         /* instantievariabelen:
          private boolean roodstuk;
         public Stuk(boolean rdstuk,final String soort){
              roodstuk = rdstuk;
         }code of the constructor of subclass Maarschalk
    public class Maarschalk extends Stuk{
         private final static int level = 11;
         private final static Figuur f = StrategoMain.figuren.getFiguur("maarschalk").scaleer(StrategoBord.portretbreedte, StrategoBord.portrethoogte);
         private final static String soort = "maarschalk";
         /* CONSTRUCTOREN:
          *Maarschalk(boolean rdstuk, soort)
         public Maarschalk(boolean rdstuk,"maarschalk"){
              super(rdstuk, "maarschalk");
         }error when trying to compile Maarschalk:
    "illegal start of type"

  • Overriding Constructor Method

    Hello,
    I want to write a class that heritances behaviour and porpoerties of the superclass. Is it possible to execute the methods of the superclass in the subclass? Instead I could write a method in the superclass and call it inside constructor of the subclass, but that seems like a trick to me.

    Is it possible to execute the methods of the superclass in the
    subclass? Instead I could write a method in the superclass and call it
    inside constructor of the subclass, but that seems like a trick to me.
    If you are talking about calling super class constructor in subclass, you can do that:
    public function SubClassConstructor(){
         super();
    If you need to call function of superclass, well, you have to write it in superclass, right? Just make it either public or protected.

  • A little question about inheritance

    Can someone explain this to me?
    I have been reading about inheritance in Java. As I understand it when you extend a class, every method gets "copied" to the subclass. If this is so, how come this doesn't work?
    class inherit {
        int number;
        public inherit(){
            number = 0;
        public inherit(int n){
            number = n;
    class inherit2 extends inherit{
        public inherit2(int n, int p){
            number = n*p;
    class example{
        public static void main(String args[]){
            inherit2 obj = new inherit2();
    }What I try to do here is to extend the class inherit with inherit2. Now the obj Object is of inherit2 class and as such, it should inherit the constructor without parameters in the inherit class or shouldn't it ??? If not, then should I rewrite all the constructors which are the same and then add the new ones??

    I believe you were asking why SubClass doesn't have the "default" constructor... after all, shouldn't SubClass just have all the contents of SuperClass copy-pasted into it? Not exacly. ;)
    (code below... if you'd like, you can skip the first bit, start at the code, and work your way down... depending on if you just started, the next bit may confuse rather than help)
    Constructors are special... interfaces don't specify them, and subclasses don't inherit them. There are many cases where you may not want your subclass to display a constructor from it's superclass. I know this sounds like I'm saying "there are many cases where you won't want a subclass to act exactly like a superclass, and then some (extend their functionality)", but its not, because constructors aren't how an object acts, they're how an object gets created.
    As mlk said, the compiler will automatically create a default constructor, but not if there is already a constructor defined. So, unfortunatley for you, there wont be a default constructor made for SubClass that you could use to create it.
    class SuperClass { //formerly inherit
    int number;
    public SuperClass () { //default constructor
    number = 0;
    public SuperClass (int n) {
    number = n;
    class SubClass extends SuperClass { //formerly inherit2
    //DEFAULT CONSTRUCTOR, public SubClass() WILL NOT BE ADDED BY COMPILER
    public SubClass (int n, int p) {
    number = n*p;
    class Example {
    public static void main(String [] args) {
    //attempted use of default constructor
    //on a default constructorless subclass!
    SubClass testSubClass = new SubClass();
    If you're still at a loss, just remember: "Constructors aren't copy-pasted down from the superclass into the subclass!" and "Default constructors aren't added in if you add your own constructor in" :)
    To get it to work, you'd have to add the constructor you used in main to SubClass (like doopsterus did with inheritedClass), or use the constructor you defined in SubClass for when you make a new one in main:
    inherit2 obj = new inherit2(3,4);
    Hope that cleared things up further, if needed. By the way, you should consider naming your classes as a NounStartingWithACapital, and only methods as a verbStartingWithALowercase

  • About method

    Look at the code below and can you tell me why the code prints out:
    SuperClass Constructor Executed
    SubClass Constructor Executed
    methodA in Superclass
    methodB in Superclass//Why not prints out methodB in Subclass,since methodB in sub has been overriden
    9
    public class Superclass {
    Superclass() {
    System.out.println("SuperClass Constructor Executed");
    private int methodB() {
    System.out.println("methodB in Superclass");
    return 9;
    int methodA() {
    System.out.println("methodA in Superclass");
    return methodB();
    class Subclass extends Superclass {
    Subclass() {
    System.out.println("SubClass Constructor Executed");
    public static void main(String[] args) {
    System.out.println(new Subclass().methodA());
    protected int methodB() {
    System.out.println("methodB in Subclass");
    return 1;
    }

    hi,but can you tell me how java virtual machine
    identify methodB() when methodA calls is the version
    of Superclass,not of Subclass?I'm not sure I understand the question?
    If methodB is private or "package", then at compile time the compiler knows which method is to be called. If the method is protected or public, then it can be overridden and the check must be made at runtime; It doesn't matter which class the method is declared in - it is called on an object, not on the class! (note that you get different behaviour with static methods, which you don't actually override, but hide, and do infact call on the class rather than an object).
    And can you tell me whether there is an instance of
    Superclass is created when an instance of Subclass is
    declared and created?No. Just a single instance of Subclass is created, but to properly initialise that instance the code in the Superclass constructor must be executed.

  • Java EE design advice for a re-designed DB app

    I'm currently tasked with rewriting a legacy DB app in Java. The original was written in Delphi. It worked great for a number of years, but the powers that be have recently decided to redesign and rewrite it in Java. Basically I just have the same set of business requirements as the original did.
    Overall, the app is a desktop GUI application that helps track contents of a natural history museum collection. The collection contains a bunch of specimens (dead animals) collected all over the globe at various times over the last 200 years. Multiple users (1 - 10 uesrs) will have to have access to the data at the same time. I also have to provide a nice Swing GUI for it.
    Here's my question: Is this the type of app that lends itself to a Java EE design? I'm imagining using a Java EE app server that connects to the DB. The app server would provide DB access, producing entity beans, as well as managing a number of session beans (EJBs) that implement the business logic (security, user management/session management). I would also have a Swing GUI that would connect to the beans remotely. This sounds like it would help me keep a good disconnect between the UI layer (Swing), the business logic (EJBs), and the data layer (entity beans accessed using the Java Persistance API). Does this sound reasonable? I'm a veteran Swing developer, but not a seasoned Java EE developer/designer.
    Also, if I use this architecture, I can imagine one issue that I might run into (I'm sure there are many others). I can imagine that I would want to retrieve the entity beans (lets say mypackage.MyPersonBean) through some call to an EJB, and then use the bean in some rendered Swing component. What happens when the Swing component needs to access the results of MyPersonBean.getAddresses() if the addresses are lazy loaded?
    As you can probably tell, I really have more than one design question here. Help/comments about any of this is greatly appreciated.

    I was thinking the same thing, but don't have a
    successful experience to validate my gut feelings.
    Here's my only suggestion (which dubwai could
    hopefully confirm or correct): write your entity
    classes/data model classes with no knowledge of
    lazy-loading etc. Then subclass them, overriding
    just the getChildren() type of methods and build the
    lazy-loading knowledge into the subclass.More or less, yes. Don't over-think it, though. If you define your basic data 'types' as interfaces, you don't need to get into complex type hierarchies or multiple versions of the types unless that becomes necessary and if it does, the changes should not affect the presentation layer.
    Since you are on-board with this and I think you are completely following, there is a technique for the lazy loading that you can use here.
    In the case where it's a one-to-one relationship, you can do the lazy-loading by creating a simple wrapper class for the child object. This class will have a reference to either null or a filled in Object. This is a little more OO because the Object is taking care of itself. Whether this abstraction is useful to you, you will have to decide.
    In the case of a one-to-many relationship, you can create a custom Collection (List or Set) that manages the stub loading. If you make a generic abstract version and subclass it for the different child types, you might be able to reuse a lot of the data retrieval code. You can do the same thing with the wrapper too.
    I will caution you to try to keep it as simple as you can without painting yourself into a corner. Only do things that you are going to use now and write things so they can be expanded upon later. Reducing coupling is a core technique for that.
    When the
    GUI asks for an object in the getData() call, hand
    them a subclass object, but don't let them know it.
    In other words, have the method "public DataClass
    getData()" return a SubDataClass object. The caller
    will only know that they received a DataClass
    object, but lazy-loading awareness will be built
    into it. This way, the lazy-loading stuff is
    completely transparent to the caller but you still
    have simple data classes that can be used outside of
    a lazy-loading context.Yes this is the idea, but don't write the other versions until you need them.
    It's also possible to use
    this method if you need to add transparent
    lazy-loading to classes that you aren't the author
    of. (Only classes that have been tagged 'final' or
    have 'final' public methods would be beyond this
    method's reach.)Yes, you can use the wrapper approach above but if the author of that class made a lot of unecessary assumptions you might have trouble.
    This approach allows for some enhancements, too.You
    can create a thread that retrieves the children of
    Foo (e.g. bars) incrementally after the Foo is
    returned to the caller. Often you can load the
    bars
    in the time it takes the user to click around to
    the
    point where they are needed or at least be partly
    done. This will make the app seem very fast to the
    user because they get the Foo very quickly (because
    you didn't load the chidren) and then the bars
    really
    quickly (because you loaded them during user
    'think-time').
    I love this idea. I'm hoping to code this into my
    GUI app soon.I would advise that you get the main lazy-loading working without this (keep in mind when writing the code) and do it once you are sure you will finish on time.

  • Passing Class T to a generic MyClass T 's constructor

    I have a class like this:
    class MyClass<T> {
        Class<T> theClass;
        MyClass(Class<T> theClass) {
            this.theClass = theClass;
    }This would require the following code to instantiate:
    MyClass<String> myClass = new MyClass<String>(String.class);Correct? This is the simplest syntax for creating the class? It seems redundant to have to pass the type "String" twice when constructing the class. I understand constructors can have type parameters like methods, but that type parameter doesn't translate the T parameter to the class, so that won't work.
    I tried the following solution:
    class MyClass<T> {
        Class<T> theClass;
        MyClass(Class<T> theClass) {
            this.theClass = theClass;
        public static MyClass<T> create(Class<T> theClass) {
            return new MyClass<T>(theClass);
    }This allows for the syntax:
    MyClass<String> myClass = MyClass.create(String.class);Which seems more elegant. Of course, the obvious problem with doing this is that it makes subclassing of MyClass much more difficult. Sometimes I can get away with this workaround, more often I cannot. Have I missed anything?

    Let's be real here. We are talking about a single line of code. Not a huge class.
    You have to change the one if you change the other. There's no danger of one
    getting left behind.I don't agree. The nature of creating a class is that for every class you create, there will be one or more (usually more, sometimes MANY more) users of that class. If it were a class like StringBuffer that is used in a million places, then you are making code less redundant for each one of those use cases, and all you had to do was add a factory method.
    You are creating a factory method on you class because of distaste for a
    syntactical construct. You don't see how this factory method changes the
    design?In a strict sense, yes, it impacts the design inasmuch as adding a method changes the contract of the class. However, I don't see how it makes any practical difference in the design.
    Are you going to create this factory method for every class that has this kind of
    situation? I imagine someone is going to come along later to maintain the
    code and think "what the..?" Yeah, and they'll click on "Go to definition" in their IDE and see the extremely complicated method:
    public static <U> create(Class<U> theClass) {
        return new MyClass<U>(theClass);
    }If they can't understand that, they don't understand generic code and probably shouldn't be mucking around there anyway.

Maybe you are looking for

  • Analog cables to connect soundblaster to receiver

    Hello. I have a Soundblaster 5.1 that I want to connect to my receiver for playing games and to take advantage of the surround sound. All the digital inputs on my receiver are being used but it does have 5.1 analog inputs. I've seen 3.5mm to RCA cabl

  • No room on nano

    HELP IVE ONLY GOT 98 SONGS ON MY NANO AND IT KEEPS COMING UP NO MORE ROOM FOR MORE WHATS GOING ON ITS A 4GB

  • MM and APO question

    Hi all, Could you please explain something to me? An order has been created automatically by the system from a requisition that was automatically generated in APO. What I don't understand is why the PO has been created so early as the master data is

  • How can i download flash player on the kindle fire

    How can I download flash player on the kindle fire

  • All of sudden my iCloud mail is working

    My icloud mail and notes have not worked for about a week.  Everytime I would check my mail on my IOS device or my mac, I would get a message saying it could not contact the server. When I went to icloud.com, it would say mail can't be loaded. Also o