Creating a Java container class - java

I have been given an java assignment in school that requires me to create a StockQuote class. This would normally be easy, however the teacher has referred to it as a simple container class. I'm confused because everything that I read says container classes are things like java.util.Vector, java.util.Hashtable, and java.util.HashSet. I get the feeling he is using this term to mean something else, perhaps even just to mean a strightforward StockQuote class. I tried emailing him but he hasn't responded and I'd like to get a jump on the assignment. Here is the description from the assignment:
"A StockQuote class or interface. This a simple container class. Typically you would not use an interface for container classes, but you could. One rule for when to use an interface or not is to decided if there ever possibly could be more than one implementation of the class. If more than one implementation is possible, then using an interface definitely makes sense. In the case of simple container classes like this one, there probably will only be one implementation"
Any help or nudge in the right direction would be great. Thanks

In your case This a simple container class. == This a simple class..
In general your class may have some fields of other types, like String, Collections, etc. If so, you would say I have a container class because it contains/stores some data.
Interfaces don't have fields, so they are not containers.

Related

What are the different types of java classes?

I'm new to SO, so if I've done this wrong, please point me in the right direction.
I think this is a bit of an awkward question, because I'm not so great at articulating my thoughts.
At university, we are taught that a java class which is written to be an object, with constructors, getters, setters, etc, are called "Container Classes". They contain data about themselves(a name attribute, for instance).
My question is what are other types of classes? For instance, you have to have a class where you create and manipulate your objects. For a small program this isn't a problem(just put it into the main class/method). For a larger program this would be silly and unmanageable, so obviously you create other classes. I've taken to naming mine "Handler"s. I have a "FileHandler" an "ObjectHandler", etc.
What type of class are these? Are there other class types out there?
Edit: To clarify, I'm wondering about what to call a category of classes, such as classes that are designed to do specific things. Helper classes? Utility classes?
Final Edit: I answered my own question here: https://stackoverflow.com/a/43964279/7985805
At university, we are taught that a java class which is itself an
object
I would have to disagree here, classes are templates for objects, you can think of them as containing a description of a particular object i.e. the object states, the behaviours that object can perform etc. An object is an instance of a class thus a class is not an object.
My question is what are other types of classes?
A class can be any type, it just depends on what you're attempting to accomplish e.g. when making a space invaders game, you could have a class of type Alien(enemies), a class of type Defender(the shooter), a class of type Bullet which the Defender can use to shoot the Aliens etc.
In my opinion if you call 'classes' 'container classes' you are only adding a redundant word.
In larger programs there could be some kind of classes that have the same purpose, e.g there could be ModelData classes, which only hold data: like employee, contract, ComplicatedCalculationResult; or there could be handler classes: FileHandler, MouseHandler, ... But all this is not set to a fixed wording.
You can name your class as it seems fit. At best name it so that someone else can guess what the class is for.
So it turns out after a bit of research, the "class types" I was trying to find names for are actually called "Design Patterns". Things like Builders, Factories, Adapters, etc.
I found a handy tutorial explaining them in further depth here: https://www.tutorialspoint.com/design_pattern/design_pattern_overview.htm
Thanks for trying to answer my very badly worded question. As I said, I'm terrible at trying to explain what I want to say.

Java extends programmatically

I am wondering about replacing Java's 'extends' keyword somehow for dynamically extending a class based on a parameter(file, environment variable, db...basically anything). Is this even possible because playing with class loaders or calling constructors does not achieve this. I am not asking "should I use interface or superclass hierarchy" rather what is extending really mean under the hood in JAVA because there aren't any good description about it just the good old inheritance jargon:
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The only way to "replace the extends keyword" is to dynamically create classes at runtime, which is entirely possible but non-trivial. Vert.x is a good example of a project that makes extensive use of dynamically-generated classes.
Java wasn't designed as a dynamic language in that sense. There are several dynamic languages out there (some of which can run on the JVM), such as JavaScript.
rather what is extending really mean under the hood...
Without getting into a long treatise on OOP, when you say Derived extends Base, it means that Derived inherits both the public and protected API of Base (which it can then add to) and also the implementation of that API. It means that code expecting to see a Base instance can accept a Derived instance, because Derived "is a" Base. This link is created a compile-time. At runtime, instantiating an instance of Derived involves all of the plumbing that instantiating a Base instance involves, plus then the added plumbing for Derived.
To achieve this you need to maintain various versions of a class based on the condition and you have to customise class loader as well because at a point when you find that you have to load a particular instance, you need to load that class which is not loaded by default class loader on JVM startup.
Its better to maintain multiple versions of the class and let JVM do its job which it does perfectly.
You can't do that with a language like Java. The information about "inheritance" is not only used by the compiler, it is also "hard-baked" into the compiled byte code.
If you really want to such kind of "dynamic" meta programming; you are better of using languages that allow you to do so; instead of "violating" a language that was never intended for such kind of usage.
To use some stupid comparison: just because you happen to know "screws" and "hammer" ... you wouldn't start to use a hammer to get those screws into the wall, would you? Instead, you would be looking for a tool that works better with "screws" than a hammer.
If you still want your code to run within a JVM; you might consider languages like jython or jruby.

Build a Separate Java Class Hierarchy

Every other class in Java inherits from the Object class.
Is it possible to add a second, completely separate, class hierarchy in Java based around my own FastObject class?
My original goal in doing so was to create smaller, faster objects with less functionality specifically designed for certain algorithms. But let me be clear, I am not interested in whether or not this is a "good idea". I just want to know if it is possible; I have not been able to find a way to do so. Would it require a change to the JVM? New boot classpath functionality? Is the real solution to ignore Object and look at replacing java.lang.Class? Would using a direct Java compiler instead of a VM make my job any easier?
To be clear, I don't just want to edit the root Object class. That would require potentially re-writing the entire Java library. I don't want to replace the current hierarchy, I just want to create a separate one I can use in the same code.
No, this is not possible.
All created classes extend another class, either explicitly or implicitly. If you create a class and explicitly define which class it extends, then it extends that class. If not, then it implicitly extends Object. There is no way around this, just as there is no way to overload operators or anything of that sort. It is a fundamental design decision of the Java programming language.
All classes extend Object. The only things that don't are primitive types. The exception to this is Object itself, of course, which does not extend itself.
It may be possible for you to inject your own Object implementation by mucking with the boot classpath. However, I don't think there is any way to use a base object other than Object. You could try some byte code manipulation, but it is entirely possible that your modified class will be rejected by the class loader.

class holding multiple instances which inherits their methods

I am pretty new to Java, so I may be using incorrect terminology. I am trying to gracefully extend a class to a new class which holds multiple instances of the superclass. For example, say I have a class
class Rose{
String smell;
Rose(String smell){this.smell=smell;}
void sniff(){ println("smells "+smell);}
}
And I want to define a class like...
class Bouquet extends Rose{
ArrayList<Rose> roses;
...
}
holding multiple roses. My actual code has something like 20 methods, and for most of them the extended method would be
void sniff(){
for( Rose one: roses) one.sniff();
}
Is there a way to construct bouquet in such a way that I don't need to explicitly define these silly loops? I'm not tied to ArrayList, I could even make a new super class if that's the way to go about it. However, it is important that I can send a bouquet instead of a rose argument to externally written methods.
EDIT:
Haha, I think my flower metaphor was a big fail. :) But your input is good; you guys have clarified my thinking a bit.
In my real problem, there are a set of operations that define how to add instances of the base class together into a new instance of the base class. Perhaps a better metaphor would be twisting a number of small fabric strands together into one rope. External methods should treat a rope and a strand exactly the same.
It does seem like extends is wrong, any other suggestions?
You dont really need to extend bouquet from roses. You extend only when there is an IS A relationship, like you have Flower class and Rose is a Flower. But bouquet is not a rose. Ideally you should have a bouquet class which HAS many roses. If there is a 1:N relationship, then you will have to loop through to get individual items.
Although we can implement anything to our desire, but there are few flaws in your class designs in regards to abstraction.
A bouquet is a collection of rose, so it shouldn't extend rose, but rather have it as a List inside it, which you have anyway. It doesn't make much sense to extend on rose and also have it as property inside bouquet. Instead, create a Base class called Flower and then extend that to create rose.
Define the sniff function inside Flower Class, making provision to override it in derived class, if you need to do that.
It would be wrong.
I would have voted Shamims answer up, if he hadn't introduced the flower class, which is not a reasonable assumption from your question.
ArrayList <Rose> bouquet;
might be all you need. But you can't use a Bouquet as a Rose. Bouquet.split (); could make sense, but Rose.split would be a very different thing.
The is-a question gives you a rough idea, whether inheritance is a reasonable thing. It's not always the final answer, but if it doesn't fit, it doesn't.
Okay, correct me if I'm wrong, but to me it seems quite obvious that the real question has nothing to do with flowers or roses, but the author is simply trying to create an example.
In a real application there could be an is-a relationship and the problem is valid. For example, I have had to use this pattern when handling callbacks: you have one MyCallback interface, a couple of concrete implementations, and to be able to register multiple callbacks you have a MultipleMyCallback class that has a list of MyCallback it delegates all calls to. You get exactly the same annoying for loop in every method.
I think you could do this via a Java dynamic proxy. Or if you're feeling adventurous even using something like CGLIB But I recommend against it. Just accept that this is a fact of life with Java and write the 20 methods and be done with it.
Without a lot of hacks, no, there is no easy way to do this. I'd highly recommend reading about this. Basically, you only want to use inheritance to enforce an is-a relationship - what this means is that your subclass should be substitutable for your base class in all situations. The natural question is therefore, is a bouquet a rose, and the answer here is no, it is not, thus inheritance is not suitable for the job.
In addendum to the answers posted, when it comes to naming your methods it will be better if you replace the sniff() method with getSmell().

Public Java class named differently than file

At one of the university classes we have to develop programs in Java. One of the requirements is to name all our files with pattern surname_firstname_exerciseN_className.java. Another requirement is that we must split our programs into multiple files. As you can imagine, these two don't play well together.
I'm trying to work around this by "translating" my class names. For example, if I write a class named "Something", I do this in my long_prefix_something.java file:
public class long_prefix_something extends Something {}
class Something {
// class code
}
And I want to use class Something in another file. So I do this in that other file:
class Something2 extends long_prefix_something { }
What bothers me, is that I can't translate long_prefix_something back to Something because of circular inheritance error, I have to use Something2 instead.
Is there anyway to overcome this? Any annotation to use or something similar?
Necessity of such hacks is usually sign of bad design. Circular (and multiple) inheritance is not allowed in java.
I agree (with other commenters) that this sounds a little scary to me... But there, nevertheless, exist a few java conventions for dealing with problems similar to yours.
It appears that you need classes which are "more descriptive" of their internal
derivation then standard java classes in an inheritance hierarchy.
Your need can be satisfied in 2 standard ways : Interfaces (compile-time) or Reflection (runtime).
Although an exact solution is not clear because you seem to have a very complex code scenario here,
the two examples can address the problem your having :
First method: By using interfaces.
1) Convert "Something" into an interface
2) Take the implmentation methods from and port them to a class SomethingImpl
3) Just have "abcde12345_something" Implement the "Something" interface.
2nd method: By using introspecting the classes.
This is a somewhat strange approach, but if interfaces won't work, you can add more hooks to your class that allow it to describe, to other objects,
what type it is derived from.
1) It is clear that you are "wrapping" classes - so , you can add an API to your wrapped classes, such that each one provides a "getRootClass()" method, like this :
public class abcde_12345_something extends Something implements RootClassProvider{
public Class getRootClass()
{
return Something.class;
}
}
2) Now, at runTime - if you can't (for some reason) when you need to do special logical operations on "Something" objects, you can
call
if(myabcd_12345.getRootClass().isAssignableFrom(Something))
Something s = (Something) myabcd_12345;
I think the best way to do what they are intending to do is to use packages, instead of cluttering the class names... I'd suggest that to your teacher if I were you:
i.e. surname_firstname.exerciseN.ClassName instead of surname_firstname_exerciseN_className.java
No, this isn't possible in Java.
Extending won't work and aliasing such as it seems you want doesn't exist in Java.

Categories