Create object of unknown class - java

I am searching for a solution to my problem for a while now but I cannot find an answer which is specific for my question.
I have a Class A which is abstract and Class B and C which extends class A. A and B are concrete classes. Class A implements function which will be inherited by V and C. Inside this function I want to create new object of B or C - the problem is that I don't know which object is that.
How can I achieve this?
public void colision(List<Organism> organisms) {
List<Organism> temp = new ArrayList<Organism>(organisms);
temp.remove(this);
for (Organizm organism : temp){
if (this.location == organizm.getLocation()){
if (this.getClass().equals(organism.getClass())){
//here is what I need to figure out
}
else{
...
}
}
}
}
}

Use Class<T>.newInstance() e.g.:
organism.getClass().newInstance().
In order to do that you need to have default constructor in your class definition otherwise you need to find constructor - e.g.:
Constructor constructor = organism.getClass().getDeclaredConstructor(parameterTypes...); and then use it like constructor.newInstance(arguments...);.

Use the Factory design pattern

Probably you can have an abstract method getInstance() in A and then have both B and C implement that method

Related

Isn't this inheritance? If not please explain

So if I instantiate a class in another class in Java, isn't that inheritance, because I am calling its method?
For example,
public void updateStock(int stockNew){
stockFinal = stockNew;
Stock stock = new Stock();
stock.update(stockFinal);
}
Isn't that inheritance, because I am able to call the method, update().
This is inheritance:
public class Base
{
public String Hello() {
return "hello";
}
public class SubClass extends Base
{
}
Then it's used like this:
SubClass sc = new SubClass();
sc.Hello(); // returns "hello"
or
Base b = new SubClass();
b.Hello(); // calls the same as above
Or this, calling the base from an overridden method:
public class SubClass extends Base
{
//#Override
public String Hello(){
return super.Hello() + " + override!!!";
}
}
The keyword super refers to the classes ancestor.
No this is not inheritance. You are just calling the class itself.
No, that's not inheritance. Inheritance is when a class extends another class. Inheritance is about establishing an is-a relationship, like a Car is a Vehicle. Or a List is a Collection.
In your example, you're just creating a new object or another type and calling a method on it. If you, of type Human, are using a car, of type Car, that doesn't make a Car a Human.
No, that isn't inheritance. Inheritance is when a class extends or implements another class. For more information go here
Here
You can find an explanation of what is OOP and its principles!
This is not inheritance.
You are just creating a object of a class.
You can use method and data member of other class but object of base class can't use method or data member of your class.
No, using a class is not the same as inheriting the characteristics of a class.
See the official Java Tutorial to learn more.

How do I select a class dynamically?

I have two classes that extends a third class, i.e.
public class class_a extends parent_class
and
public class class_b extends parent_class
My question is it possible to have a third class to create a reference to a class based on condition? i.e.
public void test() {
parent_class b;
if (cond)
b = new class_a();
else
b = new class_b();
}
Is there a way to do that?
I don't want to create variables per type of class, I will only use one throughout the life time of this function.
That is exactly what the factory design pattern is for.
http://en.wikipedia.org/wiki/Factory_method_pattern
This might also be of use Factory Pattern. When to use factory methods?
Yes.
Polymorphism allows you threat subclass as base class.
So, you can write method with parent_class return value type, like so:
parent_class create(boolean condition)
{
return condition ? new class_a() : new class_b();
}
As #John answered, it is called Factory method.
P.S. In Java, you better should name classes using CamelCase, like ClassA and ParentClass. Code style.

How can I get the implementing class for a given method?

Given a few classes/interfaces.
public interface A {
public int doSomthing(int x);
}
public class B implements A {
int doSomthing(int x){
//actually do something
};
}
public class C extends B {
//does some specific implementations of what B does
// but does NOT override "int doSomething(int)"
}
How in a code using implementation C (or any subClass of C) may I determine (programatically) that B was the class implementing int doSomething(int).
Or if any of B's subclasses (lets say D which extends C) overrid "int doSomething(int)" how, when working with E (which extends D, yeah ... this is one large family of classes) may I define first parent that implemented "int doSomething(int)" ?
Thank you all in advance :)
You can do that using reflection, i.e. you start at the class the object has and check whether that class defines the method which is identified by the methodname and parameter types. If the class doesn't define that method you get its super class and check this, until you hit Object in which case the method isn't available at all.
For public methods, it's easier since Java has already a built-in method for this:
Class<?> mostSpecificImplementor =
yourObject.getClass().getMethod( "doSomthing", int.class ).getDeclaringClass();
Note that this only works for public methods, otherwise you'd have to search up the class hierarchy yourself (use getDeclaredMethod(...) in this case).

Way to make Java parent class method return object of child class

Is there any elegant way to make Java method located within parent class return object of child class, when this method is called from child class object?
I want to implement this without using additional interfaces and extra methods, and to use this without class casts, auxiliary arguments and so on.
Update:
Sorry that I was not so clear.
I want to implement method chaining, but I have problems with methods of parent class: I lose access to child class methods, when i call parent class methods... I suppose that I'v presented the core of my idea.
So the methods should return this object of this.getClass() class.
If you're just looking for method chaining against a defined subclass, then the following should work:
public class Parent<T> {
public T example() {
System.out.println(this.getClass().getCanonicalName());
return (T)this;
}
}
which could be abstract if you like, then some child objects that specify the generic return type (this means that you can't access childBMethod from ChildA):
public class ChildA extends Parent<ChildA> {
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class ChildB extends Parent<ChildB> {
public ChildB childBMethod() {
return this;
}
}
and then you use it like this
public class Main {
public static void main(String[] args) {
ChildA childA = new ChildA();
ChildB childB = new ChildB();
childA.example().childAMethod().example();
childB.example().childBMethod().example();
}
}
the output will be
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildB
org.example.inheritance.ChildB
What are you trying to achieve ? It sounds like a bad idea. A parent class should not know anything about its children. It seems awfully close to breaking the Liskov Substitution Principle. My feeling is that your use case would be better serve by changing the general design, but hard to say without more informations.
Sorry to sound a bit pedantic, but I get a bit scared when I read such question.
Simply to demonstrate:
public Animal myMethod(){
if(this isinstanceof Animal){
return new Animal();
}
else{
return this.getClass().newInstance();
}
}
You can call this.getClass() to get the runtime class.
However, this is not necessarily the class that called the method (it could be even further down the hierarchy).
And you would need to use reflection to create new instances, which is tricky, because you do not know what kind of constructors the child class has.
return this.getClass().newInstance(); // sometimes works
I know exactly what you mean, in Perl there is the $class variable which means if you call some factory method on a subclass, even if it is not overridden in the subclass, if it instanciates any instances of $class an instance of the subclass will be created.
Smalltalk, Objective-C, many other languages have a similar facility.
Alas, there is no such equivalent facility in Java.
If you are using Kotlin, you can create an extension function
abstract class SuperClass
class SubClass: SuperClass()
fun <T : SuperClass> T.doSomething(): T {
// do something
return this
}
val subClass = SubClass().doSomething()
public class Parent {
public Parent myMethod(){
return this;
}
}
public class Child extends Parent {}
And invoke it like
Parent c = (new Child()).myMethod();
System.out.println(c.getClass());
Is this solution is correct? If it is, then, how is it different from the #1 solution?

Why is it mandatory to have a child method in Parent class to call it with a reference of parent class which is referring to an object of child class?

public class A
{ }
public class B extends A
{
public void add()
{
System.out.println("add in B");
}
}
Now here if we call add in following way hen it gives an error:
A a1 = new B;
a1.add();
But when we add the add() method in class A and then call in the similar fashion then add() method of child class is called.
i.e.
public class A
{
public void add()
{
System.out.println("add in A");
}
}
public class B extends A
{
public void add()
{
System.out.println("add in B");
}
}
call:
A a1 = new B;
a1.add();
output:
add in B
Why is it so?
at the method invocation of a1.add() the compiler checks if the method is present. But it only knows that a1 is a reference to an object of class A, which does not have that method. So the compilation fails.
In this trivial example it would probably be easy for the compiler to deduct the correct type. But in more general cases it wouldn't. And therefore this kind of logic is not part of the specs.
Because java does not know at compile time that a1 will refer to an instance of B at runtime. It only knows the declared type, so it only allows calls that work with the declared type.
When the Java compiler looks at the reference a1, it knows what methods are available. In your first example, class A does not have add() in its API. It is legal in this case to perform a cast of a1 to B like so:
((B)a1).add();
and the compiler will not complain.
You want to call a method on an object of declared type A but implement it only in a subclass B of A.
In this situation you would normally make A an abstract class and declare add() an abstract method in A.
Good answers...I had a doubt too regarding this but now I am clear :)
And one more thing ..you don't have to go into the trouble of declaring an abstract method,just make an empty method with the same name and signature in your parent class and " voila " all compilation errors are gone ;)
In your case you can add a void add(){} method like this and you wont have any problems

Categories