Question

so i got a homework from my teacher to implement a class using his interface. the name of the interface is "Position". i managed to write the code and it seems to work fine.

we are free to name our implementation-class as we want but need to define the class-name in a properties-file("ewn.properties") with the key "position-implementation" and the fully qualified classname as value position-implementation = programmieren.aufgabe4.PositionImplementation. at the end we have to export the project as a jar (my class + the properties-file).

so far so good.

now i wanted to test my solution. i created a new project, package and a main class and imported both jars (mine and the one from my teacher).

here is the code of the test-class:

public static void main(String[] args) {

    Properties prop = new Properties();
    InputStream in = Main.class.getResourceAsStream("/programmieren/aufgabe4/ewn.properties");
    try {
        prop.load(in);

        Class<?> clazz = (Class<?>) Class.forName(prop
                .getProperty("position-implementation"));

        System.out.println(clazz.toString());

        Position p = (Position) clazz.newInstance();

        p.toString();

    } catch (InstantiationException | IllegalAccessException
            | ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
}

my problem is that i don't know how to create a new instance of my implementation class. i tried to use the interface as declaration type but my object returns nothing after calling:

    p.toString();

but it should print something like this:

    ------------
    ------------
    ------------
    ------------
    ------------
    ------------

also this line:

    System.out.println(clazz.toString());

gives me the following output: class programmieren.aufgabe4.Position but it should be class programmieren.aufgabe4.PositionImplementation shouldn't it?

Was it helpful?

Solution

Question 1 : You are just doing the method call and not printing

System.out.println(p.toString());

This will print it

Question 2 : Override String toString() method in the below Implementation class as well

programmieren.aufgabe4.PositionImplementation

@override
public String toString(){
return this.class.getName();
}

Otherwise, it would invoke the toString() method belonging to any closer level super class. If it doesn't find any override of toString() method in the inheritance tree, then the Object.toString() method will be executed. Since all instances are of type Object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top