lundi 29 juin 2020

Why should we use reflection instead of direct object creation?

I'm a newbie in java and I was studying about polymorphism pattern and I encountered reflection in polymorphism. I actually don't know much about it and wanted to ask you about the benefits of it. for example I wrote this code that has an interface class name "Ieat" and some other classes that implements the eat(); method of the Ieat.

public interface Ieat {

    public void eat();
}

///////////////////////

public class Person implements Ieat{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("eat");
    }

}

////////////////////////

public class Student extends Person{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("student eat");
    }

}

//////////////////////////////

public class Worker extends Person{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("worker eat");
    }

}

///////////////////////////////

public static void main (Strings[] args){
    
    Person s = new Student;
    s.eat();

    Person w = new Worker();
    w.eat();

}

in this code I directly used "new" to create the object and override its function.

the most important question that I'm dealing with is how to use reflection and put those implementation classes in config.xml files so we can read from them? and how do we use "forName" function to do so?

I'd be thankful if you can explain it, I've been dealing with this for a loooooong time :(





Aucun commentaire:

Enregistrer un commentaire