Reflection on abstract classes

import java.lang.reflect.Method;
public class MethodInfoDemo {
     public static void printMethodInfo(final Object obj) {
          Class type = obj.getClass();     
          final Method[] methods = type.getMethods();
          for (int idx = 0; idx < methods.length; idx++) {
               System.out.println(methods[idx]);
import javax.swing.AbstractAction;
public class ReflectScaf {
     public static void main(String args[]) {
          HtmlCreator h = new HtmlCreator();
          MethodInfoDemo.printMethodInfo(AbstractAction());
}Hello again, how do you do reflection on abstract classes?
Because I can't instantiate AbstractAction I can't feed an object to the getMethods() method in the reflection class.
Any ideas?

You don't need an instance of the class in order to do reflection. You just need the class' Class object.
import java.lang.reflect.*;
public abstract class AbstractReflection {
    public static void main(String[] args) throws Exception {
        Class klass = AbstractReflection.class; // or Class.forName("AbstractReflection")
        Method[] methods = klass.getMethods();
        for (Method m : methods) {
            System.out.println(m);
    public abstract int foo();
    public abstract void bar(String str);
    public void baz() {}
:; java -cp classes AbstractReflection
public static void AbstractReflection.main(java.lang.String[]) throws java.lang.Exception
public abstract int AbstractReflection.foo()
public abstract void AbstractReflection.bar(java.lang.String)
public void AbstractReflection.baz()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public java.lang.String java.lang.Object.toString()

Similar Messages

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Instanciate generic subclass of an abstract class

    Hello,
    I'm writing a litle file manager API for my application, organised like a Database: a table filled by records.
    I want my table to be able to be able to manage different types of records (but one record type by table!), so I have this hierarchy:
    the abstract record class:
    public abstract class Record {
         public Record() {
         public abstract void readFrom(DataInput in, int length) throws IOException;
         public abstract void writeTo(DataOutput out) throws IOException;
         public abstract int prepareToWrite();
    }the abstract atomic record class, extending the abstract record class:
    public abstract class AtomicRecord<T> extends Record {
         public AtomicRecord() {
         public AtomicRecord(T value) {
              super();
         public abstract T getValue();
         public abstract void setValue(T value);     
    }and, for example, the StringRecord class:
    public class StringRecord extends AtomicRecord<String> {
         code doesn't matter.
    }now, I want to make a table of generic records:
    public class RandomRecordAccessAppendableFileTable<RecordType extends Record>{
         public final RecordType getRecord(long id) throws IOException {
              RecordType record = new RecordType();
    }problem: the RecordType is obviously not instanciable, as it extends Record, and not StringRecord. But I still want to instanciate a new StringRecord from a RandomRecordAccessAppendableFileTable<StringRecord> and a FooRecord from a RandomRecordAccessAppendableFileTable<FooRecord>.
    Is there a way I can do this?
    Thank you in advance.

    This is just my opinion, so you might ignore it: The design you are targeting is a result of misunderstanding what Generics are for and what Generics may provide in their current state. Their only purpose is to provide compile-time type safety. Creating instances the way you want to do seems more runtime focused, i.e., when generic information is gone.
    Maybe, you should consider passing a factory at construction time that enables to create a record of a specific type. Using the class object requires reflection, which will introduce implicit contracts to record classes and potential runtime failures.

  • 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.

  • 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.

  • Interfaces vs abstract classes

    hi,
    i have some kind of general idea about interfaces and abstract classes.but what are the situations that are most suitable for use interfaces and abstract classes..if u have any idea pls help me
    thanx and best regards,
    Kelum

    BigDaddyLoveHandles wrote:
    Reason for using interfaces #17: dynamic proxies.
    import java.lang.reflect.*;
    interface Fooable {
    void f();
    void g(int x);
    class Foo implements Fooable {
    public void f(){ System.out.println("Foo.f()"); }
    public void g(int x){ System.out.format("Foo.g(%d)", x); }
    public class ProxyExample implements InvocationHandler {
    private Fooable target = new Foo();
    public static void main(String[] args) {
    Fooable fooable = (Fooable) Proxy.newProxyInstance(
    Fooable.class.getClassLoader(),
    new Class[] { Fooable.class },
    new ProxyExample());
    fooable.f();
    fooable.g(17);
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Invoking: " + method.getName());
    return method.invoke(target, args);
    <cat position_relative_to_pigeons="among">
    Although libraries like ASM or CGLIB allow you to dynamically proxy classes, too
    </cat>

  • Inheritance, abstract classes

    Hi peeps!
    There's Train class with collection of RailCar
    RailCar is made up of SleepingCar and SaloonCar
    and OccupiableSpace is made up of Berth and Seat
    *RailCar makes use of OccupiableSpace(Abstract Class)
    Is following hierarchy correct?
    OBJECT
    ^
    |
    Train
    ^
    |
    RailCar (Abstract class)
    ^________ ___________^
    |________ __________ |
    1) SleepingCar 2) SaloonCar (these two classes extends RailCar)
    and for remaining classes
    OBJECT
    ^
    |
    OccupiableClass (Abstract Class)
    ^ __________ ____ ^
    | ______________ |
    1)Seat 2) Berth (these two classes extends OccupiableSpace)

    I don't think you need to that abstract here to create a Train class
    is a - the class is extended
    has a - the class has members to reflect the data you wish to store for the class operations (methods) that will act upon that data
    RailCar.class // does not have to be abstract unless you want to defer (or later enforce) some implementations in the subclass
    SleepingCar IS A Carriage
    Carriage HAS A berth
    I think the route 'implements Sleepers' and 'implements Sitters' with an interface for each may give you a more solid design if you want some abstraction in your model.

  • What is the diff b/w Abstract class and an interface ?

    Hey
    I am always confused as with this issue : diff b/w Abstract class and an interface ?
    Which is more powerful in what situation.
    Regards
    Vinay

    Hi, Don't worry I am teach you
    Abstract class and Interface
    An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
    Edited by SASIKUMARA
    SIT INNOVATIONS- Chennai
    Message was edited by:
    sasikumara
    Message was edited by:
    sasikumara

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • ".. is an abstract class.  It can't be instantiated"

    Does anyone have an idea of how I can get rid of the above error message? Here is a bit of my code:
    import java.io.*;
    import java.util.Vector;
    class Project3 {
    private BiTree company = new BiTree();
    public static void main(String[] args) throws IOException {
    Project3 run = new Project3();
    run.Command();
    public void Command() throws IOException {}
    public interface comparable {
    //not sure if need this in this class, or at all
    public int compare(Object object1,Object object2);
    public void add() {
    Employee newOne = new Employee();
    System.out.println("Enter name");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String name = stdin.readLine();
    System.out.println("Enter title");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String title = stdin.readLine();
    System.out.println("Enter payrate");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    payrate = Double.parseDouble.stdin.readLine();
    newOne.setTitle(title);
    newOne.setName(name);
    newOne.setPayrate(payrate);
    company.insert(newOne);
    }

    It is not possible to create instances of an abstract class.
    I hope this example helps,
    abstract class Vehicle
    public static void main(String arg[])
    Vehicle a;
    a = new Automobile(); // ok, since Automobile is a kind of Vehicle
    // The class Automobile, a special case of Vehicle
    class Automobile extends Vehicle

  • Abstract Class can't be instantiated

    Hi I'm getting the following error messages while compiling. Does any one have any idea how to get RID of it?
    ERROR MESSAGES:
    EditableHeaderTableExample2.java:48: inner class EditableHeaderTableExample2. MyComboRenderer is an abstract class. It can't be instantiated.
    MyComboRenderer renderer = new MyComboRenderer(items);
    ^
    EditableHeaderTableExample2.java:79: Method redefined with different return type: javax.swing.table.TableCellRenderer getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int) was java.awt.Component getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
    public TableCellRenderer getTableCellRendererComponent(
    ^
    2 errors
    Here is the code:
    EditableHeaderTableExample2.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JComponent;
    import javax.swing.JComboBox;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.JTable;
    import javax.swing.plaf.metal.*;
    import javax.swing.JFrame;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    public class EditableHeaderTableExample2 extends JFrame {
    public static void main(String[] args) {
    EditableHeaderTableExample2 frame = new EditableHeaderTableExample2();
    frame.setSize(400,300);
         frame.setLocation(100,100);
         frame.setVisible(true);
    public EditableHeaderTableExample2(){
    JTable table = new JTable(10,10);
    TableColumnModel columnModel = table.getColumnModel();
    table.setTableHeader(new EditableHeader(columnModel));
    String[] items = {"Dog","Cat"};
    JComboBox combo = new JComboBox();
    for (int i=0;i<items.length;i++) {
    combo.addItem(items);
    MyComboRenderer renderer = new MyComboRenderer(items);
    EditableHeaderTableColumn col;
    // column 1
    col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(1);
    col.setHeaderValue(combo.getItemAt(0));
    col.setHeaderRenderer(renderer);
    col.setHeaderEditor(new DefaultCellEditor(combo));
    // column 3
    col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(3);
    col.setHeaderValue(combo.getItemAt(0));
    //col.setHeaderRenderer(renderer);
    col.setHeaderEditor(new DefaultCellEditor(combo));
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    class MyComboRenderer extends JComboBox implements TableCellRenderer
    MyComboRenderer(String[] items) {
    for (int i=0;i<items.length;i++) {
    addItem(items[i]);
    public TableCellRenderer getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelectedItem(value);
    return this;

    This is not a suggestion, it's a requirement. When you say
    class MyComboRenderer extends JComboBox implements TableCellRendererthe "implements TableCellRenderer" part is a promise that your class will include a method whose signature is
        Component getTableCellRendererComponent(JTable table, Object value,
                                 boolean isSelected, boolean hasFocus,
                                 int row, int column);

  • Difference between abstract class and the normal class

    Hi...........
    can anyone tell me use of abstract class instead of normal class
    The main doubt for me is...
    1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../

    Class vs. interface
    Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
    For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
    With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
    This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
    Interface vs. abstract class
    Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
    Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

Maybe you are looking for

  • ITunes running as a process in Task Manager but not opening up

    Hi all I got an iPod nano a week ago, and since I installed the CD for the iPod on my computer, iTunes doesn't open. I removed QT and iTunes and the iPod updater and reinstalled them, but to no avail. I took my computer to the local Apple store and t

  • How do you print two-sided in In Design when some sections have an odd number of pages?

    I'm new to In Design, and I'm trying to do something that seems pretty basic and having trouble figuring out how to do it, and I haven't found anything in the Adobe Forum or online that addresses this situation. I am working on a document that is bro

  • I need to reverse this problem, code included

    Hello, I am trying to master Java and I have a long way to go. I am still trying to get a grip on the fundamentals. I have a program (the code is below) that I am trying to manipulate and get to do something a little different then it does. The progr

  • How to create ddl for partitioning for a child table?

    Hi folks, I am new to the partitioning topic. I red some manuals and tutorials but I did not found exactly what I need. So I would ask for your help. I have two tables. The partitioning of the master table is clear: create TABLE ASP_PARTITION_TABLE_M

  • Splitting Documents by Bookmark

    I am having trouble splitting documents by bookmark. I continue to get this error message: This file may be read-only or another user may have it open. Please save the document with a different dame or in a different folder. Other Documents have work