JUnit to test abstract class?

Folks:
I am new to JUnit and currently writing some testing code using it. I am wondering if it's necessary to test an abstract class/interface. If so, how? Do I need to create a mock object that extends it to test it?
Thanks a lot!!!

Here's one (of thousands) of the ways you might choose to test an abstract class.
public MyAbstract foo;
public void setUp() {
   foo = new MyAbstract() {
      public void myAbstractMethod() {
         // Do nothing, or whatever
public void testBar() {
   final String spong = foo.bar("Hello");
   assertTrue(spong.equals("World"));
}In the above we create a testable instance by deriving an anoynmous inner class from it.

Similar Messages

  • Question about abstract class

    Hi,
    I am doing some junit tests with given class.
    However, i cannot touch the original class(or even create any new class).
    All i can do is to create JUnit test class
    This class is abstract and has only one public void method.
    Also, this class is extended by several child classes which are either
    abstract / or public but methods are private/protected.
    So i cannot even create an object of this class by using
    ParentClass pc = new ChildClass();
    Is there any method to test this class without using mock-objectm, and without touching the original class?
    Thanks in advance

    Hi,
    I am doing some junit tests with given class.
    However, i cannot touch the original class(or even
    create any new class).
    All i can do is to create JUnit test class
    This class is abstract and has only one public void
    method.
    Also, this class is extended by several child classes
    which are either
    abstract / or public but methods are
    private/protected.What is meant by abstract / or public.
    However the public method in the base class cannot be
    overidden to be private or protected.
    >
    So i cannot even create an object of this class by
    using
    ParentClass pc = new ChildClass();
    Is there any method to test this class without using
    mock-objectm, and without touching the original
    class?
    Thanks in advance

  • Help with abstract classes

    Hi All,
    1. I would like to know if an abstract class can contain a main method?
    2.I have a class called KeyTest which is a junit test class and it contains 2 methods called testSymKey() and testAsymKey() which bascially tests for symmetric key generation and assymmetric key generation. My manager has asked me to create an abstract test class for this class and define the methods in the abstract class and then make a subclass of this abstact class. I am not sure how this can be done!! Any help is appreciated.Here is what i have till now
    public class KeyTest extends TestCase implements CSFConstants
    public static void main(String[] args) throws Exception
    junit.textui.TestRunner.run(suite());
    protected void setUp() {
    public static Test suite()
    return(new TestSuite(KeyTest.class));
    public void testSymKey() throws CSFException
    CSFISymKey loSymKey = CSFManager.getInstance().getSymKey();
    loSymKey.init();
    loSymKey.generate();
    assertTrue(loSymKey.save() != null);
    public void testASymKey() throws CSFException
    CSFIAsymKey loAsymKey = CSFManager.getInstance().getAsymKey();
    loAsymKey.init();
    loAsymKey.generate();
    assertTrue(loAsymKey.getPublicKey().toString() != null);
    assertTrue(loAsymKey.getPrivateKey().toString() != null);

    If a class has one or more abstract methods (including if it claims to implement an interface but doesn't provide an implementation for one or more of the interface's methods, which are all implicitly abstract), then the class must be declared abstract.
    However, the converse is not true. An abstract class can have all abstract methods, a mix of abstract and concrete methods, all concrete methods, or no methods at all. You can take any class you want and declare it abstract. (Of course, if you do, any code that does new ThatClass(); will now not compile.)

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • Final field in abstract class

    Hi ... consider the code:abstract class It {
         protected final boolean
              USE;
    public class Test extends It {
         public Test(){
              USE = true;
    } upon compiling there is an error (infact, two errors).
    final may not be assigned, can't assign to final.
    of course, if "It" was not abstract, the first error might be true ... but it is abstract, so
    shouldn't this checking of assignment to final be delayed until the class is inheritied
    as concrete ? it would seem to make sense ... i can't see a reason for this not being
    the case.
    if it was the case, we could delay assignment until our constructor of "Test" where it
    would assign to the final variable of "It".
    it shouldn't be an error, should it ?
    java version:java version "1.4.2_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_03-b02)
    Java HotSpot(TM) Client VM (build 1.4.2_03-b02, mixed mode)

    is it because references to the final fields are resolved at compile-time ?
    such that the compiler must know the value of USE in:if(USE){
      // a
    // b at compile time so it can remove either "b" or "a". I think so. hmm.

  • Lookinf for a "flexible" abstract class mechanism

    When writing an abstract class, or an interface, is there a way to force the classes who extends it to implement at least one method in a set of 2 ?
    For instance,
    public abstract class PermanentCard {
       public void concretePlayByPlayer(Player parPlayer);
       public void concretePlayByPlayer(Player parPlayer, Location parLocation);
    }In this case, I'd like to say that all class who implement PermanentCard must implement at least one these two methods.
    Is there a way to avoid multiplying the number of abstract I have?

    bestam wrote:
    To BigDaddy :
    Consider I have an abstract class who expects its implementations to implement a concretePlay method, whatever is its signature. Of course, java is only able to distinguish methods via their signatures.
    I was just looking for non-direct way to let the implementations implement one or another, but at least one.
    Supposing you did that, how is the code using the interface to know which method(s) are available in this particular implementation? An interface is a contract, and the user is entitled to expect that contract to be fulfilled.
    If you have some classes which do things one way, and some the other, it would be better to put the two method signatures in different interfaces, in which case the code using the class could us instanceof to test which method signature was actually available.
    The two interfaces could extend a common, possibly empty one for references that might hold either.
    Of course in this particular case using the same signature with a null argument is more satisfactory.
    Edited by: malcolmmc on May 14, 2009 9:20 AM

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • Abstract class methods

    I'm confused. Is this true or false.
    The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
    Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

    Yes. You are - pretty much.
    The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
    Silly example:
    abstract public class Animal {
       public Animal() {
       public abstract int getNumberOfLegs();
    }That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
    public class Cat extends Animal {
       public Cat() {
          super();
       public int getNumberOfLegs() {
          return legCount;
       public void maim(int legsToRemove) {
          legCount -= legsToRemove;
          if(legCount < 0 ) legCount = 0;
       private int legCount = 4;
    }A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
    Java even provides a special operator to test this:
    Cat cat = new Cat();
    System.out.println("A cat is a cat: " + (cat instanceof Cat));
    System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
    D.

  • Abstract class instantiation.?

    I have an Abstract class which is extended
    My question is:
    How can the Abstract class be instantiated:
    Animal[] ref = new Animal[3];
    In Java,we cannot instantiate Abstract class,so how does this
    work
    abstract class Animal  // class is abstract
      private String name;
      public String getName(){       
           return name;
      public abstract void speak();  
    class Dog extends Animal{
          private String dogName;
          public Dog(String nm){
         this.dogName=nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Woof");
          public String getName(){   // Override default functionality.
              return dogName;
    class Cow extends Animal{
          private String cowName;
          public Cow(String nm){
          this.cowName = nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Moo");
          public String getName(){
              return cowName;
    public class AnimalArray{
      public static void main(String[] args) {
      Animal[] ref = new Animal[3]; // assign space for array
      Dog aDog = new Dog("Rover");  // makes specific objects
      Cow aCow = new Cow("Bossy"); 
      // now put them in an array
      ref[0] = aDog;
      ref[1] = aCow;
      // now dynamic method binding
      for (int x=0;x<2;++x){
           ref[x].speak();
           System.out.println(ref[x].getName());
    }

    You mean to say that now we have a handle or a reference to the
    abstract class. Right ?
    But in the
    public static Test instance () {
            return new Test () {
                public void test () {}
        }How can you say 'return new Test()' as Test is an abtract class
    and what will public void test() return as this has no body ?

  • Abstract class, a question

    i have an abstract class called shape with default constructor (double y1, double y2);
    with an abstract method area.
    now i have a circle class which extends it, but i want its constructor to have ONE radius (as its pi radius*radius)
    at the moment this is how my circle looks like, and as you can see that there is really no need for second radius how can i modify circle class without modifying shape class?
    class circle extends Shape{
    circle(double radius, double radius1) {
         super(radius, radius);
    double area() {
    return (3.14*x1*x1);
    }

    the answer from the test class in above case will be
    0!Yes, because 3.14 * 0 * 0 is 0.
    but if i change the x3 above to x1, it would work, You honestly don't see why? It's staring you right in the face. What does area() use? How does that field get set?
    the
    reason i decided to use x3 is so that ppl dont get
    confuse! Here's what's confusing:
    * field names x1, x2, x3. What do those mean? They sound like 3 x coordinates.
    * two fields that are used by certain subclasses, but not others, and a third field that's used only by the subclasses that don't use the first two.
    * that third field meaning "the single value that applies to what both of the other two fields mean" instead of just setting both fields to the same value.
    * having any of those fields in there at all in the first place when they're not used by the abstract class and not used consistently by subclasses.
    but shouldnt it work because i have done the
    same thing i did to x1 and x2??

  • Abstract class causes JNI GetByteArrayElements to crash

    I'm having a problem with a subclass of an abstract class that is accessing a JNI function. I'm using Java 1.4.2.
    I started out with a single class that reads data from a serial port (via a JNI call) and then parses the data. When I test this class, the read/parse works correctly.
    Since I have to create multiple parsing protocols, I decided to create an abstract class that contained the reading functionality and a subclass that parses the data. When I did this, the 1st call to GetByteArrayElement never returns (nor do I get a stack dump trace).
    I also tried making the super-class non-abstract and over-writing the prase method(s). I got a similar failure.
    I can't imagine what the issue might be - why would splitting the original object into two (superclass/subclass) cause such a problem?
    I've include relevent snippits of code.
    Thanks for the help!
    ===== JNI Code =====
    extern JNIEXPORT jint JNICALL Java_vp_jni_Serial_read (JNIEnv *env,
         jclass class, jint fd, jbyteArray buf, jint cnt, jint offset)
         jboolean     iscopy = JNI_FALSE;
         // FAILS ON CALL; NEVER RETURNS!!!!
         const jbyte *data = GetByteArrayElements (env, buf, &iscopy);
         const uchar     *b;
         int               num,
                        rc;
         b = (uchar *) &data[offset];
         num = cnt;
         do
              rc = read (fd, (char *) b, num);
              if (handleReadException (env, rc) != 0)
                   (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
                   return rc;
              num -= rc;
              b += rc;
         } while (num > 0);
         (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
         return cnt;
    }==== Java Native Calls ====
    public class Serial
         public int read (byte[] data, int length, int offset)
              throws IOException
              return read (fd, data, length, offset);
         private static native int read (int fd, byte[] buf, int cnt, int offset)
              throws IOException;
    }==== Abstract super-class ====
    package vp.parse;
    import java.io.IOException;
    import java.io.InterruptedIOException;
    import java.io.SyncFailedException;
    import vp.jni.Serial;
    import vp.jni.Exec;
    import vp.data.ControlData;
    public abstract class Parse extends Thread
         protected static final int     ERROR = -1;
         private static final int     LOC_TIMEOUT = 3000;
         private Serial          link;
         private int               port;
         private boolean          running = false;
         private int               baud = Serial.B9600;
         protected abstract void reset ();
         protected abstract void parse ();
         public Parse (int port, String id, int baud)
              this.port = port;
              this.baud = baud;
              start ();
              synchronized (this)
                   try
                        wait (5000);
                   } catch (Exception e)
                        System.out.println (id + " Thread failed to synchronize");
              System.out.println ("Done");
         public void run ()
              link = new Serial(port);
              try
                   link.open();
                   link.setBaud (baud);
                   link.setTimeout (LOC_TIMEOUT);
              catch (Exception e )
                   link = null;
                   return;
              running = true;
              synchronized (this)
                   notify ();
              while (running)
                   parse ();
         protected int read (byte[] buf, int packetSize, int offset)
              if (offset >= packetSize)
                   offset = 0;
              if (offset > 0)
                   for (int i=0; i<packetSize - offset; i++)
                        buf[i] = buf[offset+i];
                   offset = packetSize - offset;
              try
                   int cnt = link.read (buf, packetSize - offset, offset);
                   offset = 0;          // all data is good
              // ready to 'close down' executable
              catch (Exception exp)
                   running = false;
                   return ERROR;
              return offset;
    }==== Sub-class to handle parsing ====
    package vp.parse;
    public class Eis extends Parse
         private static final int     PACKET_SIZE = 3 + 69 + 1;     // hdr, data, csum
         private byte[]          buffer = new byte[PACKET_SIZE];
         private int               offset = 0;
         public Eis (int port)
              super (port, "GR EIS", Serial.B9600);
         protected void reset ()
              offset = 0;
         protected void parse ()
              do
                   offset = read (buffer, PACKET_SIZE, offset);
                   if (offset == ERROR)
                        offset = 0;
                        return;
                   // parse code here
              } while (parse failed);
         public static void main (String[] argv)
              Eis e = new Eis (3);
              try { Thread.sleep (10000); } catch (Exception x) {}
    }

    The issue was the following:
    I had declared a buffer in the sub-class;
    private byte[] buffer = new byte[PACKET_SIZE];
    And the assumption would be that by the time it got used, it would be initialized. But that's not the case. Why?
    The sub-class called the super class constructor. At this point in time, buffer[] is not valid.
    The super class constructor spawns the child thread and waits for the spawned thread to finish initialization.
    The spawned thread creates the serial port, informs the constructor it's 'done' and starts to parse incoming data.
    The parse() code is the sub-class passes the uninitialized buffer to the JNI code and GetByteArrayElements crashes because id doesn't like a null pointer.
    Since the parent thread doesn't regain control to finish the construction, buffer[] never gets initialized.
    So much for synchronized thread spawning in a constructor...

  • Casting to an abstract class from a different classloader

    I have a class Special that extends an abstract class Base. In my code I use a URLClassLoader to load the class Special and I then want to cast Special to Base. If I do this I get a ClassCastException because the classes are loaded from different classloaders. I can't have the URLClassLoader and the class that performs the cast extend a parent ClassLoader that knows about the Base class. What I want to be able to do is something like this:
    URLClassLoader loader = new URLClassLoader(codebase, null);
    Class baseClass = loader.loadClass(className);
    Base baseObj = (Base)baseClass.newInstance();
    I have seen some post that suggest I can achieve this using Reflection but I am not sure how to go about this. Any help would be appreciated.
    Thanks
    Jim.

    Thanks for your help so far but I still can't do the casting, consider this example:
    //Base.java
    package classTest;
    public interface Base
         public abstract void execute();
    //ConcBase.java
    package classTest;
    public class ConcBase implements Base
         public void execute()
              System.out.println("execute in ConcBase called");
    I compile these files and jar them into work.jar
    I now have my application:
    //Test.java
    import java.net.*;
    import java.io.*;
    import classTest.*;
    public class Test
    public static void main(String[] args)
              Test t = new Test();
              t.test();
         public void test()
              try
                   File file = new File("D:/Projects/classloadTest/work.jar");
                   URL[] codebase = {file.toURL()};
                   ClassLoader ccl = getClass().getClassLoader();
                   ccl.loadClass("classTest.Base");
                   URLClassLoader ucl = new URLClassLoader(codebase,ccl);
                   Class conClass = ucl.loadClass("classTest.ConcBase");
                   classTest.Base b = (classTest.Base)conClass.newInstance();
                   b.execute();
              catch(Exception t)
                   System.out.println("thowable caught");
                   t.printStackTrace(System.out);
    I compile this and run it with this command:
    java -classpath D:\Projects\classloadTest\work.jar;. Test
    This runs as I would expect, however I have set the parent class loader of my custom URLClassLoader to the one that does the cast, this means that Base and ConcBase are both being picked up by the application class loader as my custom class loader delegates to its parent. This is the current behaviour I have in my proper application and it is causing problems, I don't want the class that implements Base to delegate to any class on the main applications classpath. If I change the line:
    URLClassLoader ucl = new URLClassLoader(codebase,ccl);
    In Test.java to:
    URLClassLoader ucl = new URLClassLoader(codebase,null);
    I get a ClassCastException, this is because the class that does the cast (Test) loads Base from it's classpath and ConcBase is loaded from the URLClassLoader. After spending more time looking at this problem I don't think there is anyway to resolve but if anyone thinks there is please tell me.
    Many thanks
    Jim.

  • Question about abstract classes

    abstract class Animal
    abstract boolean alive();
    class Dog extends Animal
    public int age;
    class Test
    public void main(String args[])
    Animal a = new Dog();
    a.age = 2; // <== Doesn't work, why?
    }

    abstract class Animal
    abstract boolean alive();
    class Dog extends Animal
    public int age;
    class Test
    public void main(String args[])
    Animal a = new Dog();
    a.age = 2; // <== Doesn't work, why?
    }because a is an "Animal" and you didn't specify that all "Animal"s have an "age" - only that "Dog"s do. So of course you would have had to do:
    Dog a = new Dog();
    a.age = 2;
    (It still wouldn't have compiled anyway however, because you didn't implement the "alive" method in Dog)

  • About  "abstract class cannot have be instantiated"

    in java coding it means
    ========
    abstract  class X
      public X();
    }========
    no {} is allowed to public X
    or i can not write a invoke as
    ========
    X x=new X();========
    or both of them are forbidden by abstract class?
    why body{} is related to instantiated?
    why a abstract class can not has a static method?

    in java coding it means
    ========
    abstract class X
    public X();
    ========
    no {} is allowed to public X???
    You must include the braces for the constructor. The code you have posted won't compile.
    or i can not write a invoke as
    ========
    X x=new X();
    ========Correct. You need to provide the implementation first, which can be as simple as "X x = new X() { };".
    why body{} is related to instantiated?It's not.
    why a abstract class can not has a static method?It can. Try writing some of your own tests to validate your (incorrect) assumptions.
    Example:abstract class X
      public X() { };
      static void foo() {};
    }

  • Dynamically invoke methods of abstract class?

    Hi,
    I am using reflection to write a class (ClassA) to dynamically invoke methods of classes. I have an abstract class (ClassB) that has some of the methods already implemented, and some of the methods that are declared abstract. Is there any way that I can:
    (a) invoke the methods that are already implemented in ClassB;
    (b) I have another class (ClassC) that extends ClassB, some of the methods are declared in both classes. Can I dynamically invoke these methods from ClassB?
    Thanks in advance,
    Matt.

    Ok, the program is quite long, as it does other things as well, so I'll just put in the relevant bits.
    What I have is a JTree that displays classes selected by the user from a JFileChooser, and their methods.
    // I declare a variable called executeMethod
    private static Method executeMethod;
    // objectClass is a class that has been chosen by the user.  I create a new instance of this class to execute the methods.
    Object createdObject = objectClass.newInstance();
    // methodName is the method selected by the user.  objectClassMethods is an array containing all the methods in the chosen class.
    executeMethod = objectClassMethods[j].getDeclaringClass().getMethod(methodName, null);
    Object executeObject = executeMethod.invoke(createdObject, new Object[]{});Ok, here are the test classes:
    public abstract class ClassB{
         private int age;
         private String name;
         public ClassB(){ age = 1; name="Me";}
         public int getAge(){ return age; }
         public String getName(){ return name; }
         public void PrintAge(){System.out.println(age);}
         public void PrintName(){System.out.println(name);}
         public abstract void PrintGreeting();
    public class ClassC extends ClassB{
         public ClassC(){super();}
         public void PrintAge(){
              System.out.println("I am " + getAge() + " years old.");
         public void PrintGreeting(){
           System.out.println("Hello");
    }Now, I can print out the PrintAge method from ClassC (i.e. have it output "Hello" to the command line, how can I, say, get it to output the result of PrintName from ClassB, this method does not appear in ClassC. As you can see at the top, I can create a new instance of a normal method (in this case, ClassC), and have it output to the command line, but I know that I can't create a new instance of an abstract class. And since PrintName is implemented in abstract class ClassB, how do I get it to output to the command line?
    Thanks,
    Matt.

Maybe you are looking for