I have two classes:
public abstract class Parent{
Object parentObj;
public abstract Object something();
}
And
public class Child extends Parent{
#Override
public Object something(){
return new Object();
}
}
Is there any way to do something in the parent to set parentObj every time the something() method is called?
I don't want to set parentObj in every child.
Sure:
public abstract class Parent{
Object parentObj;
public final Object something() {
parentObj = ...;
return doSomething();
}
protected abstract Object doSomething();
}
and
public class Child extends Parent{
#override
protected Object doSomething(){
return new Object();
}
}
That's called the template method pattern.
Related
is there a way to automatically initialize a subclass when the parent-class is initialized(constructed)?
For example like this:
public class Parent {
public Parent() { //Constructor
...
}
public class Child {
public void foo() {
...
}
}
}
I want to be able to do something like this:
Parent p = new Parent();
p.Child.foo();
Any Ideas? I think it's all about static-ness but I'm not sure, so any help is appreciated. Thanks in advance.
You cannot call it that way.
If the child class must be a non-static class and reside inside a parent class then you will have to initiate it either in the parent class or outside of it before using any of its methods.
You have this option.
public class Parent {
private Child child;
public Child getChild() {
return child;
}
public Parent() { //Constructor
this.child = new Child();
}
public class Child {
public void foo() {
...
}
}
}
After that you can call the foo() method this way.
Parent p = new Parent();
p.getChild().foo();
Maybe somehting like that:
public class Parent {
public Parent() { //Constructor
foo();
}
protected void foo() {
// Do nothing in parent
}
}
public class Child {
#Override
public void foo() {
...
}
}
Edit: this is not a correct anwser as Child does not extend Parent.
Try this code:
This first part is the main. You have to invoke que Parent and make an instance the Child (That is the first lane of the code) After that, you can use the child methods.
Parent child = new Parent().new Child();
child.foo();
On the other hand, the class:
public class Parent {
public Parent(){
}
protected void foo(){
}
public class Child extends Parent{
public Child(){
}
#Override
public void foo(){
System.out.println("I am the child!!");
}
}
}
As you can see that is very similar that you have, but you have to write in the child "extends Parent" to specify the parent of that class.
I hope that could help you!!!
I want to invoke a private method which takes abstract class parameter and that abstract class is hidden (I can not access it directly). I need to get the updates whenever methods of abstract class are invoked by some other class.
Class I am refereeing to is:
public class A{
private void method(AbstractClassA object){ ... }
// please note below class is hidden. I can not do A.AbstractClassA . I have to access it using reflection unless there is any other way
public abstract class AbstractClassA {
//I am interested in getting this int whenever someone else calls the progressUpdate
public void progressUpdate(int update);
}
}
I am trying to access like this:
public class myClass{
Class<?> abstractClass = Class.forName("<package>.A$AbstractClassA");
A a = new A();
Method someMethod = a.getDeclaredMethod("method", (Class[])null);
someMethod.setAccessible(true);
someMethod.invoke(a, <something which I don't know>); //how to pass paramerts here so that I get all callbacks whenever progressUpdate is called by someone else and "update" parameter is changed.
}
public class SubClassA extends A {
private SubClassAbstractA subClassA;
public SubClassA() {
this.subClassA = new SubClassAbstractA();
}
public class SubClassAbstractA extends AbstractA {
#Override
public void progressUpdate(int update) {
SubClassA.this.progressUpdate(update);
}
}
public void progressUpdate(int update) {
//do things with int
}
public void someMethod() {
Class<?> clazz = A.class;
Method method = clazz.getDeclaredMethod("method");
method.setAccessible(true);
method.invoke(this, subClassA);
}
}
public class Parent {
....
}
public class Child1 extends Parent {
....
public void foo() {
....
}
}
public class Child2 extends Parent {
....
public void foo() {
....
}
}
Here method foo() only exists in the Child classes and CAN NOT be added to the Parent class (not even abstract method). In this situation when I want to call the foo() method on obj which is Parent class's reference then I need to use intanceof with multiple if..else which I want to avoid.
Parent obj = ...// Object of one of the child classes
obj.foo();
EDIT: I Need to use type of obj as Parent only. Else I will not be able to call methods on obj which exists in Parent class.
My Solution: The approach that I am thinking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
Is there a better approach ? Or any improvement to this one?
You can't do it with parent object reference until an unless method is declared in parent class/interface itself.
You have to downcast it to child class because parent class/interface doesn't have any knowledge about the child class other than the contract defined between them.
Here contract means abstract methods.
you can try in this way where there is no need to put a check it.
FooInterface sc =new Child1();
sc.foo();
...
interface FooInterface{
void foo();
}
public class Parent {
}
public class Child1 extends Parent implements FooInterface{
public void foo() {
}
}
public class Child2 extends Parent implements FooInterface{
public void foo() {
}
}
The approach that I am finally taking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:
Parent obj = ...// Object of one of the child classes
.....
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
The polymorphism is applied on object reference, not a type. When you call
FooInterface obj = ...// Object of one of the child classes
obj.foo();
the child class method foo() is called.
If you want to typecast only then there is no need of adding interface. You can typecast it to your desired class and call the method. Example
public class HelloWorld {
public static void main(String args[]) throws FileNotFoundException {
SuperClass sc =new Child1();
if(sc instanceof Child1)//Do same for Child2
((Child1)sc).foo();
}
}
class SuperClass {
}
class Child1 extends SuperClass{
public void foo(){
System.out.println("From child1");
}
}
class Child2 extends SuperClass{
public void foo(){
System.out.println("From child2");
}
}
Output :
From child1
You could implement an AbstractChild inheriting from Parent and then extend this class instead of Parent:
public class Parent {
....
}
public abstract class AbstractChild extends Parent{
public abstract void foo();
}
public class Child1 extends AbstractChild {
....
public void foo() {
....
}
}
public class Child2 extends AbstractChild {
....
public void foo() {
....
}
}
So you need to only check if your instance is instanceof AbstractChild.
Is it possible to dynamically identify T as a return type depending on subclass Type?
I want something like the following:
public class Parent {
public <T extends Parent> T foo() {
return (T)this;
}
}
public class Child extends Parent {
public void childMethod() {
System.out.println("childMethod called");
}
}
And then to call:
Child child = new Child();
child.foo().childMethod();
Without defining the type like so:
Child child = new Child();
child.foo().<Child>childMethod(); // compiles fine
Thanks in advance!
You want this:
public class Parent<T extends Parent<T>> {
public T foo() {
return (T)this;
}
}
public class Child extends Parent<Child> {
public void childMethod() {
System.out.println("childMethod called");
}
}
Child child = new Child();
child.foo().childMethod(); // compiles
It is impossible in the Java type system for Parent to refer to the exact class of this. However, it can have a type parameter (say T) that subclasses can specify, as either themselves, or some other type (whatever they want), and use an abstract method to delegate the task of obtaining an instance of a that type T to the subclass.
public abstract class Parent<T> {
// the implementer is responsible for how to get an instance of T
public abstract T getT();
// in this case, foo() is kind of redundant
public T foo() {
return getT();
}
}
public class Child extends Parent<Child> {
public Child getT() {
return this;
}
public void childMethod() {
System.out.println("childMethod called");
}
}
Child child = new Child();
child.foo().childMethod(); // compiles
I am implementing my first Decorator pattern. The base class which I want to decorate has a member variable initialized in the constructor. The decorated class also has this member variable (since it is a descendant of the base class). My question is, should I initialize this member variable in the decorated class too, or use the member variable of the base class (which lives inside the decorated class)?
Here is some code. I'm just curious whether Decorated1 or Decorated2 is better?
public class Base{
private String memberVariable;
public Base(){
memberVariable = "";
}
public Base(String s){
memberVariable = s;
}
public String Description(){
//code here
}
}
public abstract class BaseDecorator(){
public abstract String Description();
}
public class Decorated1 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
b = _b;
}
public String Description(){
//code here
}
public String getMemberVariable(){
return b.getMemberVariable();
}
}
public class Decorated2 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
super(_b.getMemberVariable());
b = _b;
}
public String Description(){
//code here
}
public String getMembervariable(){
return memberVariable;
}
}
You have to figure out what this variable means for your class, or if it is really needed, but i would suggest that no.
interface IObject{
//declare methods
void doSomething();
}
class ObjectA implements IObject{
private int variable;
public void doSomething(){
}
}
class DecorateObject implements IObject {
private IObject decoratedObject;
public void doSomething(){
decoratedObject.doSomething();
//do more things
}
}
if IObject is a drawable element, it would have x,y coordinates that would be inherited so it is correct to put on a superclass, in this case it would be an abstract class.
interface IObject{
//declare methods
}
abstract class AbstractObject implements IObject{
private int xCoordinate;
}
class ObjectA extends AbstractObject {
}
class DecorateObject extends AbstractObject {
private IObject decoratedObject;
}