Passing a custom object in Java - java

I know this is probably pretty basic, and I'm ashamed for not knowing how to do this (and worse yet, being unsuccessful in searching for a solution).
How would I pass an object of type thing from A to C?
public class A extends B {
}
public class B {
public class thing {
}
}
public class C extends JFrame {
}
I have access to thing in A because I'm extending B, but I'm unable to extend B when using class C because I need to extend JFrame.
EDIT
Sorry for the vagueness. Class A has a collection of objects of type thing and I want to iterate through those objects in class C.
EDIT 2
And of course... the obvious choice. Make thing its own class... :(
Admitting shame for the sake of those who may also have an issue like this.

First, if it's an inner class - you probably shouldn't access it from the outside...
But, if you insist, you can try to do as follows:
public class A extends B {
}
public class B {
public class thing {
}
private thing mything = new thing();
public thing getThing(){
return mything;
}
}
public class C extends JFrame {
A a = new A();
Object thing = a.getThing();
}

accessing an inner class from the outside is generally a bad idea, but if you must i wold suggest looking at the delegate design pattern like in this article :
delegate design pattern

You probably trying to use multi-inheritance which is not possible in java!
you can use interfaces to have 2 different behavior or Use some design patterns
to achieve such a goal.
It's really unclear what you are trying to do.however see composite or factory-method patterns
i think it could help.

Related

How to use an abstract iterator (of the la4j library)?

It's a bit hard to phrase my question. I'm struggling a lot with using libraries in java currently and often are not really sure how to efficiently use them. In theory I know what an interface and an abstract class is but it seems that in practice these things are hard for me to use.
So, to be more specific, as an example, in the moment I'm using a CCS matrix from the la4j library. I now want to iterate over it (the rows and every entry in each of these rows) and want to use the library for it but I find only abstract iterators (e.g. the RowMajorMatrixIterator). In general: I don't know what to do with abstract classes (or interfaces) from libraries. Specifically in this moment and as a typical instance of my problem: If I have this abstract iterator, how do I actually use it (for my CCS Matrix)?
Every help is appreciated!
You get the iterators from the matrices you created beforehand: the class Matrix defines a method rowMajorIterator(), for example, so you can do
RowMajorMatrixIterator it = yourMatrix.rowMajorIterator();
This pattern is called "Factory Method".
As Thomas points out, it is often implemented as some sort of inner class, like this:
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new RowMajorIterator() { // anonymous class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
}
or
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new MyRowMajorIterator();
}
class MyRowMajorIterator extends RowMajorIterator { // inner, named class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
These inner classes have access to the members of the "outer" class Matrix.

Generic parent object cannot be returned as child without cast

This question might resemble cast the Parent object to Child object in C# but it is about C# and I have a question about Java.
I am also aiming to make a generic builder. The generic builder should only build the parts of the abstract object and the children all manage the induvidual implementations of the abstract class.
abstract class GenericBuilder<B extends GenericBuilder>
{
//lots of build methods
public B lastBuildingMethodInTheChain(Object someValue)
{
//assignment
return this;//<-- is not allowed!
}
}
But when I put in a cast:return (B) this; it is fine.
The cast is something I want to prevent, but this also restricts the children builders from using their special methods.
The last thing makes sense because the Generic type is only known at runtime, but I have no clue how to write it so that it would work at compile time.
Thank you!
You can see an example of the typesafe progressive narrowing pattern (a name that I probably just made up) in various Guava builder methods. In the end, the cast is necessary, but you can hide it reasonably well like so:
#SuppressWarnings("unchecked")
private <B1 extends B> GenericBuilder<B1> me() {
return (GenericBuilder<B1>) this;
}
used like so:
public B lastBuildingMethodInTheChain(Object someValue) {
B self = me();
self.assignWhatever = someValue;
return me;
}
(I'm not 100% sure this will work exactly as-is because of the extra weirdness you've got, with the object being parameterized as a subclass of itself.)
Here are some similar examples to draw from:
Subclassing a Java Builder class
http://egalluzzo.blogspot.com/2010/06/using-inheritance-with-fluent.html
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205
Note the use of the getThis() method which avoids the cast.
The correct way to declare GenericBuilder is with an f-bound type:
abstract class GenericBuilder<B extends GenericBuilder<B>> {
public B lastBuildingMethodInTheChain(Object someValue) {
// assignment
return (B) this;
}
}
You can't avoid the cast, as the compiler needs it to know that this generic builder is actually the concrete builder of the generic type parameter.
You can extend the generic builder as follows:
public class ConcreteBuilder1 extends GenericBuilder<ConcreteBuilder1> {
}
It is reasonable to assume the cast is safe. The only way for the cast to fail would be to declare i.e.:
public class ConcreteBuilder2 extends GenericBuilder<ConcreteBuilder3> {
}
But why would you ever do that?
This makes no sense. this is a GenericBuilder, and B extends GenericBuilder, so how are you going to return this (since GenericBuilder does not extend itself (tautologically)

Java: How do I add to a base class without modifying class file

I am using a Java library that has a class hierarchy:
e.g. classes C1 and C2 that both extend class B
Is there a way for me to add functionality (attributes, methods) to class B such that it will be available to the child classes C1 & C2 without modifying the 3 files?
If not, what is the right way to do this short of rewriting all 3 classes?
Assuming you aren't able to modify B for some reason, make an intermediary class that extends it for you:
public class ClassC extends ClassB {
//additional functionality
}
Then it's simple:
public class Class1 extends ClassC {...}
If you can modify B, the other classes already inherit the methods, and you don't need to worry about rewriting them unless you mark the methods abstract
If you cannot modify B then you will have to extend it, and modify C1 and C2 to extend your new class instead of B.
If you cannot modify any of these classes, then you could do something like this:
Create BX extending B with new functionality
Create C1X extending BX, and containing an inner C1 object. Delegate all method calls except the new methods in BX to the underlying C1 object
Create C2X following the same logic as C1X
This ain't pretty. And might not work. For example if the new method needs to manipulate private data of the underlying objects then this won't work. But I don't think there's another way, given the restrictions. If Java had multiple inheritance it could work by C1X extending both C1 and BX, but short of that I'm afraid this dirty solution is the best you can have. (If it even works.)
Is there a way for me to add functionality (attributes, methods) to class B such that it will be available to the child classes C1 & C2 without modifying the 3 files?
You will only have to modify the class B. If you add methods, they will be inherited by classes C1 and C2 automatically, so you don't need to modify those classes.
You only need to modify class B. If you add a protected or public method to B, C1 and C2 will automatically be able to invoke it, without any changes required.
Seems the question is kind of vague and it is hard to tell without knowing your intention.
If you want to enhance the behavior of your class in runtime, then you may look into something like Javassit or CGLib etc, which allow you to alter the classes and add new feature to it, without need of modifying source code of the original source.
If you are developing something, and trying to find a design that will allow you to add functionality without changing source code of existing classes, then you may look into things like Dectorator pattern.
If you simply have that three class on hand and you don't want to/not allowed to modify them but you still want to add functionality without updating them. Then it is not possible in Java, sorry. (A lot other languages provide such feature anyway)
You'll have to modify class B in any case. There can be 2 approaches to this(assuming you can modify B).
First: Make the changes you want to do in B directly and since C1 and C2 extend B already, the methods and fields would be available in those classes as such(only if they are public or protected, that is). This requires a lot of changing in B though.
Second: Have an abstract class which is extended by B. In this case, a small change to B should suffice which would be extending that abstract class. This way, everything you add to the abstract class is available to all the classes below in the hierarchy. Just make sure you don't have any abstract methods in the abstract class.
public abstract class ParentOfB {
// Additional functionality
}
public class B extends ParentOfB { // The only change in B
}
The reason why ParentOfB is abstract is because you don't want any other class using those functionality without inheriting B. In case you need that functionality elsewhere, you can make ParentOfB just a normal class.
This is the answer I came up with. It's a variation of what Janos wrote but I think it is nicer. I do not need to change any of the classes, can re-use the extension in any of the children classes and continue to inherit from the new extended children. Still need to delegate the methods though.
So for example:
Note how D1 below already inherits from B1, C1 and B_EXTRA_IMPL
public class B1 {
public void b1() {
System.out.println("B1");
}
}
public class C1 extends B1 {
public void c1() {
System.out.println("C1");
}
}
-------------------------- Adding New B1 Functionality to C1 ---------------------
public interface B_EXTRA {
void b_extra();
}
public class B_EXTRA_IMPL implements B_EXTRA {
public B1 m_b1;
B_EXTRA_IMPL(B1 base) {
m_b1 = base;
}
#Override
public void b_extra() {
System.out.println("b_extra");
}
}
public class C1X extends C1 implements B_EXTRA {
B_EXTRA_IMPL b_extra;
C1X() {
super();
b_extra = new B_EXTRA_IMPL((B1)this);
}
public void b1()
{
System.out.println("B1");
}
#Override
public void b_extra() {
b_extra.b_extra();
}
}
public class D1 extends C1X {
}
public class Main {
public static void main(String[] args) {
D1 d = new D1();
d.b1();
d.c1();
d.b_extra();
}
}
Just modify class B. No need for changes in other files.

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.

Calling super class method inside implemented abstract method

Basicaly I have a need for several methods that do the same thing but with different parameters the sub-classes can chose from, and still force the implementation.
Is this a correct approach/design ?
EDIT: I have edited the addItem() body, these methods contain the final logic that is used to handle the passed parameters
public abstract Class A {
public abstract void addItemImpl()
addItem(String s) {
// do stuff
}
addItem(Collection c) {
// do stuff
}
addItem(Item item) {
// do stuff
}
}
public Class B extends A {
addItemImpl() {
addItem("text, text2")
}
}
public Class C extends A {
addItemImpl() {
addItem([item, item2])
}
}
No, this will not work.
You will not be able to define the "doStuff()" method because you have to handle the parameters. You provide not enough information to give you detailed help. But it's possible that generics might come in handy:
public abstract Class A<T> {
public addItem(T t) {
// dostuff with t
}
}
public Class B extends A<String> {
}
public Class C extends A<Collection> {
}
This is a perfect case for: Favor composition over inheritance.
Your subclasses don't fully benefit from the superclass and don't depend on its implementation details. Then define an interface for the contract B and C must obey (addItemImpl()) and compose them with A.
Ask yourself: is B really an A? is C really and A?
What you have is technically correct, but with out knowing what addItem actually does it is difficult to know if this is the best solution. My guess would be that there probably is a better way.
If addItem essentially set values to be used in the doStuff, I would just do that work in the Class B and C instead. Any others that need to do it the same way as B could extend it instead of A.
Edit: Based on your edit, I would say this is probably a bad example to use an abstract class. There is no truely shared functionality. An interface would be more appropriate as you need a different implementation for each. You are just trying to hide that inside an abstract class. I would change A to an interface along with using generics.
Only go the abstract class route if there is actually shared code that is exactly the same in all the classes without having to do any tricks to make it work (like above).
If you need force implementation for few methods, then Abstract methods are ideal.
But be careful only the very first Non-Abstract sub-class of the Super-class is bound to implement all the abstract methods in it....

Categories