Is it worth to put instance of class inside interface? - java

I'm trying to learn some basics about OOP in Java.
I read about interface. My question is: is it worth to use instances of class inside interface? I'm not sure, but I think it could reduce amount of instances among code, e.g:
public interface mergingInterface
{
ArrayClass ac = new ArrayClass();
LinkedListClass llc = new LinkedListClass();
}
then I just can do:
public class LinkedListClass implements mergingInterface
{
LinkedList link = new LinkedList();
public void filling()
{
ac.someMethodFromArrayClass();
//some method
}
}
and many classes may use one object. Is it worth? Is my thinking correct?

No! The point of an interface is that it's decoupled from its implementations. Any class should be able to implement it without having to modify it. In your example, you would have to modify mergingInterface to have an instance of every implementer.

Related

What is the correct way to implement a Creator Class and the Class itself design in Java?

I am trying to decide on a design for all my classes and their creators.
For example I have 2 classes, Level and LevelLoader:
The design I have come so far is:
This is Level class:
public class Level implements Serializable {
private byte[] map;
Level(LevelLoader loader){
map = loader.getMap();
}
// ...
}
This is the Creator:
public interface LevelLoader {
public Level loadLevel(InputStream stream);
public byte[] getMap();
}
So for example to create a level instance in main file I'll write:
TextLoader is implementing LevelLoader interface above:
File file = new File("src/Level/level2.txt");
Level level1 = new Level(new TextLoader(file));
So I am curious what is the most logical way to connect them to the other?
certainly you will have more implementations in the near future. So without directly creating instances like TextLoader, get them using a Factory.
Sorry I quite not get what question is about?
perhaps:
- you need to create many instances of your Level class during application run time
- also you may need different kind of loaders (TextLoader, FileLoader, URLLoader and so on..)
Then you can create each loader once somewhere outside (i.e. Utiltiy or ObjectFactory class) and then reuse them to create instances.
something like that:
ObjectFactory class
private static LevelLoader filetLoaderInstance = new FileLoader("level2.txt");
private static LevelLoader urlLoaderInstance = new URLLoader("ftp://foo.com/level2.txt");
public static Level createLevelFromFile()
{
return new Level(textLoaderInstance);
}
public static Level createLevelFromURL()
{
return new Level(urlLoaderInstance);
}
In general without necessity of multiple usage such design is not needed.
Like in your example with
Level level1 = new Level(new TextLoader(file));
It is quite overhead. What is the reason to have and create another object (TextLoader) if it will run only once?
But if that code has to run many times - it is not good. It is better to have only one instance of TextLoader rather than create it every time when instance of Loader class creates.
It affects memory usage as well as performance of application.
What I feel is the below way.
InputStream is = new File("src/Level/level2.txt");
LevelLoader levelLoader = new TextLoader();
Level level = levelLoader.loadLevel(file);

Questions on classes extending from a base class (Java)

I'm a beginner in Java trying to write a system of party quests for a game that I'm currently writing and I have a few questions I'd like to be answered. I've already gone around and asked other people, but they're not familiar in Java.
In the past I'd tried making a bunch of classes and accessing them with multiple get methods. I found that incredibly tedious to write and thought I could unify them under an abstract class/implemented class. Thus, the code looked more like this ...
DynastyPQInterface pq = new CustomPQ // or ....
DynastyPQInterface pq = new OtherCustomPQ
Of course, this presented difficulties such as being only able to use implemented methods. It didn't allow me to access the class' exclusive methods that I might want to use later on.
Ultimately, what I want to do is to be able to use a single get method to return any of these derived classes, but still retain the ability to just universally use the get method to call methods that they have in common, such as execute, create, end, while simultaneously allowing me to reach out to their exclusive methods specifically. Is there a way to do that, or is it impossible?
If it's still not clear ...
The code I have write now is a base class that is extended to the other classes in the manner ...
DynastyPQ (base) -> methods include (run(), execute(), end())
CustomAPQ (inherited from DynastyPQ) -> (has exclusive methods like getPoints())
CustomBPQ (inherited from DynastyPQ) -> (has exclusive methods like revivePlayer())
I want to write a get method so to rid myself of multiple. What I have right now is ...
DynastyPQ dynastyPQ;
DynastyPQ getPQ() {
return dynastyPQ;
}
void setPQ(DynastyPQ pq) {
dynastyPQ = pq;
}
Doing this ...
DynastyPQ pq = new CarnivalPQ();
I can only access DynastyPQ's methods rather than Carnival's methods.
Is there a way to access the exclusive methods while universally being able to execute the four base functions without regard to the type of class, or did I miss something earlier?
tl;dr -> I want one get method that universally returns all classes that inherit from class X; however, I want to be able to access each class's exclusive methods.
You can probably just cast the object to the derived class:
DynastyPQ pq = new CustomAPQ();
((CustomAPQ)pq).customAPQmethod();
If you don't know what is the dynamic type (the type you used after the new operator), you can use the instanceof keyword:
DynastyPQ pq = getPQ();
if (pq instanceof CustomAPQ) {
CustomAPQ a = (CustomAPQ)pq;
a.customAPQmethod();
} else if (pq instanceof CustomBPQ) {
CustomBPQ b = (CustomBPQ)pq;
b.customBPQmethod();
} else {
// Neither a CustomAPQ nor a CustomBPQ.
}
If you don't want to do that, you can use polymorphism:
class DynastyPQ {
final void run() {
// code.
}
final void execute() {
// code.
}
final void create() {
// code.
}
void specific1() {}
void specific2() {}
}
class CustomAPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomAPQ.
}
#Override
void specific2() {
// do stuff specific to CustomAPQ.
}
}
class CustomBPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomBPQ.
}
#Override
void specific2() {
// do stuff specific to CustomBPQ.
}
}
Now, you can do:
DynastyPQ pq = new CustomAPQ();
pq.specific1();
The called method will be CustomAPQ::specific1(). If specific1() was not declared in CustomAPQ, then, it will just do nothing.
Other than #CelineNOEL suggested it is not possible. Because you declared a class of type DynastyPQ, you can call only methods defined inside that class. In the moment you want to call specific method, not shared one, you know from which class it is and you can use casting to call that specific method.
((CustomAPQ)pq).customAPQmethod()
Shared methods you are using in code, when you don't know which class should execute same peace of code(or you want it to execute it different if you override share methods in every sub-class), and you delegate it to be resolved in runtime. So reconsider your design and in base class put methods that needs to be called dynamically. All other methods you are sure are specific for one class put only in that class. On that way your code will be cleaner and you will not mess thing that should be separated.

How to Prevent instantiation of concrete classes?

Lets say I have a Record Interface and I can have N number of its concrete implementation classes eg. PropertyRecords,LoanRecords etc.How do I ensure there is no object of these N classes is created by client using new keyword?
Its quite easy if I have a single subclass;I can Make all the constructors package private;so that I can write a Factory class in the same package which will have a method which will be responsible for creating instances.But how to create a virtual Factory able to create several implementations of a single interface or abstract class.
Hope i am able to put myself correctly.Please ask if any clarification needed.
Thank you.
Not sure why you would want this, but your Factory class can use reflection to create instances like this:
public class RecordFactory {
public Record newInstance(Class<? extends Record> klass, Object... args) {
Constructor[] ctors = klass.getDeclaredConstructors();
// find the right constructor here..
return ctor.newInstance(args);
}
}
Then your clients can create instances like:
RecordFactory.newInstance(Loan.class, ...);
I'm not entirely sure I understand what you're trying to achieve (comment on this is not), but here are my thoughts:
Sounds like what you really want is to implement the Flyweight design pattern (http://en.wikipedia.org/wiki/Flyweight_pattern).
If you really want to implement this as you describe it (again, under the assumption that I understood correctly), the following should work:
public class Record {
private static final int MAX_INSTANCES = 20;
private static volatile int instanceCounter = 0;
private Record() {
if (instanceCounter >= MAX_INSTANCES)
throw new RuntimeException("max instances exceeded");
instanceCounter ++;
}
}

Accessing class methods through objects

Edit: Have edited to provide more spefic code
As you can see my sprite drawing is breaking this rule.
I would be really grateful if someone could explain by way of pseudo code based on my code below (This is because I've read many explanations of this rule but I still don't really understand why it's a problem or how to do what I need to do without breaking this rule :-( )
1) Why would this cause a problem in my code?
&
2) Please explain an alternative way of doing what I'm attempting to do (while keeping a separate resource class that is specifically for loading my resources and creating my sprite objects).
Is there anything wrong with accessing objects through 2 or more class objects. I will explain through some code:
Here I have 3 classes, is there anything wrong with accessing the method from class2 through another object as in the third class below..........:
Code
My Resource Class
//Resource class
public Class Resource(){
Bitmap myTexture;
Quad mySprite;
public void LoadResources(){
//Load graphics
myTexture = BitmapFactory.decodeResource(view.getResources(), R.drawable.myBitmap);
//Create my objects
mySprite = new Quad(); //Create new Quad object
mySprite.setTexture(myTexture); //Set texture to this quad
mySprite.setSize(100,100); //Set size of this quad
}
}
My Quad Class
public class Quad(){
//This custom class has the bulk of the code to create all of the Quads / Sprites
public void setTexture(Bitmap textre){
//etc.....
}
//etc....
}
public void draw(int x, int y){
//Draw code here
}
And finally, my main GLRenderer class:
public class MyGLRenderer implements GLSurfaceView.Renderer{
Resource res;
public MyGLRenderer(){
res = new Resources(); //Create object to my resources
}
public voide onDrawFrame(){
//Here is my main loop and I need to draw my sprites here, so........
res.mySprite.draw(x, y); //Draw my sprite
}
Why it's bad to have several chained method calls
The law this violates
This violates a coding practice known as the law of demeter. This law states that you should only talk to those classes "next to you".
Why this is a bad thing
The reason for this is because, by calling methods in several other classes, your class needs to know about those methods, and depends on those methods changing. This is called close coupling. If the methods change, you need to change lots of code in other classes. This is called "Shotgun Surgery" and isn't a desirable feature in a program!
A possible solution
Look into the proxy design pattern. It's primarily designed to provide an interface to another class, and it might help you here. Perhaps by having a reference to both objects, this class can provide a common interface for all methods to talk via and reduce the coupling between the classes.
Edit to help with your example
Your example isn't actually that bad. You get an object, and you make a method call on it. The dependency comes in one form: If you remove the mySprite field from your class, your code won't work, and if you remove the draw method from your sprit it won't work. To me, the easiest solution is to add a Proxy method to your Resources class, called draw() that accepts a sprite as an argument.
Secondly, perhaps instead of accessing mySprite directly, you can put it through a method. Let's say you had a member that looked like this:
private ArrayList<Quad> sprites = new ArrayList<Quad>();
This means that in order to gain access to these sprites from the outside, you would need to have some sort of method. Now, by forcing other classes to talk via these methods, you're reducing coupling. This is because the original class only needs to know the one method in another class, and the other class will do the work. Then you wrote a drawSprite method that looked something like:
public void drawSprite(int index) // Index really is up to you {
sprites.get(x).draw();
}
Now I know it might have more parameters than that, but it only means one method call from your MyGLRenderer class, hence conforming to the law of demeter, and reducing coupling in your classes.
Sorry, but it wouldn't work...
As Mike pointed out, Classes instantiated in any of SomeClass's methods are "alive"/valid only when you're inside the method. This means that the instantiated object is specific to the method, and can't be accessed outside the method.
A possible solution:
The solution to this is to add a SomeClass2 member to SomeClass. If you instantiate this member in SomeClass's constructor, it'll stay alive till SomeClass is in scope, making it available for you to use. The code would look something like this:
SomeClass:
class SomeClass
{
// Define the class attributes. This class can be then accessed publicly
SomeClass2 class2
// Constructor - Instantiate all your members here
public SomeClass()
{
// Instantiate class2 in the constructor
this.class2 = new SomeClass2();
}
// Your method which does what you need
public void classMethod()
{
class2Object.class2Method();
}
}
SomeClass2 will stay the same
And SomeClass3 will be:
class SomeClass3
{
public void class3Method()
{
SomeClass classObject = new SomeClass();
// Call the instantiated member and then call it's method
classObject.class2.class2Method();
}
}
This should compile/run. I would comment on the design, but I'll wait to find out what you're planning to use this for before I do! :)
It will work (except you your SomeClass2 object is declared within the method, and it should be within the class as a member variable, but I assume that's a typo).
But I would consider using getters and setters instead (it's considered better practice):
class SomeClass{
private SomeClass2 class2Object = new someClass2();
public SomeClass2 getClass2Object() { return class2Object; }
}
class SomeClass2{
public void class2Method(){
//Some code here
}
}
SomeClass3{
public void class3Method(){
SomeClass classObject = new SomeClass();
classObject.getClass2Object().class2Method();
}
}

Inheritance and casting: is this good java?

Take a look at this code (from here)
abstract class EntityA {
AssocA myA;
abstract void meet();
}
abstract class AssocA {
int something;
abstract void greet();
}
class AssocAConcrete extends AssocA {
void greet() {
System.out.println("hello");
}
void salute() {
System.out.println("I am saluting.")
}
}
class EntityAConcrete extends EntityA {
void meet() {
System.out.println("I am about to meet someone");
((AssocAConcrete)myA).salute();
}
}
There are two parallel inheritance trees, for a parent class and an associated class. The problem is with line 23:
((AssocAConcrete)myA).salute();
It is a pain and I have that kind of thing all over my code. Even though that line is part of the concrete implementation of Entity, I need to remind it that I want to use the concrete implementation of AssocA, AssocAConcrete.
Is there some kind of annotation to declare that relationship? Or is there a better, more colloquial Java way to express this design? Thanks!
This is in response to #Dave, because I want to put some code in...
Interesting! So the invocation would look something like this:
AssocAConcrete myAssoc = new Assoca();
EnitityA<T extends AssocA> myEntity = new EntityA<AssocAConcrete>();
myEntity.setAssoc(myAssoc);
myAssoc.salute();
Yes? That's really cool. I think I will use it!
I would think this is a lot neater using generics...
abstract class EntityA<T extends AssocA> {
// Basically, this means myA is at least an AssocA but possibly more...
T myA;
abstract void meet();
}
abstract class AssocA {
int something;
abstract void greet();
}
class AssocAConcrete extends AssocA {
void greet() {
System.out.println("hello");
}
void salute() {
System.out.println("I am saluting.");
}
}
class EntityAConcrete extends EntityA<AssocAConcrete> {
void meet() {
System.out.println("I am about to meet someone");
myA.salute();
}
}
Aside from avoiding the casting, this also makes it much easier to add different functionality in your AssocA implementations. There should always be a way to do things without using dummy implementations (ie methods that just throw "NotImplementedException") or casting. Even though it isn't always easy or worth the refactoring time to do so. In other words, no one is going to blame you for casting (well...maybe some people will but you can't please everyone).
EDIT (Notes on instantiation):
From #pitosalas' comments below...
//Won't work...can't call 'new' on abstract class AssocA
AssocAConcrete myAssoc = new Assoca();
//Instead, do this...
AssocAConcrete myAssoc = new AssocAConcrete();
And then....
// Again, won't work. T is only declaring the type inside your class/method.
// When using it to declare a variable, you have to say EXACTLY what you're making,
// or at least something as exact as the methods you're trying to invoke
EnitityA<T extends AssocA> myEntity = new EntityA<AssocAConcrete>();
//Instead do this...
EnitityA<AssocAConcrete> myEntity = new EntityAConcrete();
// Or this...
EntityAConcrete myEntity = new EntityAConcrete();
And then this should be good...
// Assuming this is defined as `public void setAssoc(T newAssoc) {this.myA = newAssoc;}`
myEntity.setAssoc(myAssoc);
myAssoc.salute();
Looks suspicious to me. There is nothing terrible about casting, but in this case, you could resolve the issue by bringing the salute method into AssocA. Subclasses of AssocA can provide their implementations; that's part of the benefit of inheritance.
What you are doing now is saying all EntityA instances have an AssocA instance, but then in your meet method you basically force the AssocA instance to be an AssocAConcrete instance. That's the part that is suspicious; why does AssocA exist if you really need an AssocAConcrete.
Another option (based on your comments) is to invoke salute in the greet method. That way, the specific subclass has specified behavior greet, defined in the superclass, and does what it wants. In this case, salute could become private or protected. Another implementation can easily do something different, like runLikeHell.
The problem of parallel class hierarchies is very real and really sucks. The logical coupling that AssocAConcrete always go with EntityAConcrete can not be expressed with the type system.
You can not specialize the type of myA in EntityAConcrete to be AssocAConcrete, without hiding it from a superclass. I think the closest work that addressed that was "Family polymorphism", but that's not mainstream.
If you have a large part of code where you are using the reference "myA" you could declare another reference like that:
public AssocAConcrete myAConcrete = (AssocAConcrete)myA;
now you can use the new reference myAConcrete and access the functions of the AssocAConcrete Class.
If you need to do this a lot like hvgotcodes mentioned you should probbably consider moving the method up to the AssocA Class.

Categories