This site requires JavaScript, please enable it in your browser!
Greenfoot back
divinity
divinity wrote ...

2017/8/1

how to get around an instantiate object

divinity divinity

2017/8/1

#
hi danpost, super_hippo I am doing a hospital program for the longest time. my question is how do you get around to use an instantiate object. without removing the abstract from the other class.
Super_Hippo Super_Hippo

2017/8/1

#
I am not sure if I understand what you mean, but you can not instantiate an object of an abstract class, but you can instantiate an object of a non-abstract class even if it is a subclass of an abstract class.
danpost danpost

2017/8/4

#
I will try to explain a little more clearly. Suppose you have an abstract class, AbstractClass. You cannot do this:
1
AbstractClass obj = new AbstractClass();
This is what Hippo was trying to say. However, if you have a subclass of that class:
1
public class NonAbstractClass extends AbstractClass { }
then, you can create an object of type AbstractClass by instantiating the NonAbstractClass class:
1
AbstractClass obj = new NonAbstractClass();
In fact, the World and Actor classes of greenfoot are abstract classes; yet, you can create worlds and actors nonetheless because you instantiate their subclasses. You can instantiate an object of an abstract class while supplying the code for the subclass (a subclass that is not given a specific name):
1
AbstractClass obj = new AbstractClass(){};
The empty code block used can have code inserted to modify the behavior of or add extra state to that of AbstractClass. For example, suppose you want to create Actor objects that are not to move in a scrolling world. You could use the following method to create them from in your World subclass:
1
2
3
4
public Actor getNewStaticActor()
{
    return new Actor() { public void setLocation(int x, int y){} };
}
The actor created and returned will be immune from being relocated as the implementation of the 'setLocation' method is absent (no executable code is given for the method; so, calling it does not do anything).
You need to login to post a reply.