Implementing parent class methods with several children class in Java - java

I have a class (let's call it A) that is extended by several children class (B, C, D, etc.).
In each child class, there are specific methods that I'd like to be accessible from an instantiation of the parent class A.
I tried to declare A as an abstract class, and to declare each child class methods inside as abstract. Then I implemented these methods in their own class but it seems that each child class must implement every method of the parent class. However, I can't do this.
Would you have an idea for this issue?

In each children class, there are specific methods that I'd like to be accessible from an instantiation of the parent class A.
That's not the point of inheritance. Even if you could do this, it shows that your design is broken.

Related

How can the Object class be a super class of subclasses?

Fact 1:
Java does not support multiple inheritance.
Fact 2:
Object is a superclass of all other classes
If I have a class Parent and a class Child which is inheriting the class Parent:
class Parent {
}
class Child extends Parent {
}
In this case, how will the class Child inherit the Object class, if Java does not support multiple inheritance?
How is the relationship between these three defined?
Option 1:
Option 2:
It's Option 2. If you define a superclass, that will be the immediate superclass of your class. If you don't define one, Object will be the immediate superclass.
class Parent {
}
class Child extends Parent {
}
is equivalent to
class Parent extends Object {
}
class Child extends Parent {
}
So, while Object is the superclass of all classes, there might be some steps in the class hierarchy before you get to Object. It's not the immediate superclass of all classes.
Object might not be a direct parent, but it's always a super parent.
Child extends Parent
Parent extends Object
|
V
Child [indirectly] extends Object
The JavaDoc says:
Class Object is the root of the class hierarchy. ...
If a class does not extend any other class by decalring it using the keyword extends it extends though implicit from Object.
The documentation says:
In the absence of any other explicit superclass, every class is
implicitly a subclass of Object.
See the Example 8.1.4-1 "Direct Superclasses and Subclasses" in JLS, chapter 8.1.4
It shows that a class Point { int x, y; } "is a direct subclass of Object"
Moreover the documentation says:
Classes can be derived from classes that are derived from classes that
are derived from classes, and so on, and ultimately derived from the
topmost class, Object. Such a class is said to be descended from all
the classes in the inheritance chain stretching back to Object.
The JLS states it short and formal:
The subclass relationship is the transitive closure of the direct
subclass relationship.
Thus class Object is the superclass of all classes.
But the documentation also says:
Excepting Object, which has no superclass, every class has one and only one direct superclass (single
inheritance).
Going on with the example a class ColoredPoint extends Point { int color; } "is a direct subclass of class Point.". By the transitive relationship it's a (non-direct) subclass of class Object.
Summarizing:
Object is either the direct superclass or by transitive relationship the last superclass of any other class.
Answering the questions:
Java does not support multiple inheritance: It provides single inheritence in a transitive way. Every class extends directly only one supercalss.
How is the relationship: The class Parent corresponds to the class Point and the class Child to the class ColoredPoint of the JLS example. Only Option 2 shows this relation.
Well it is an interesting discussion. I think it will be option no 2. As if you try the below code .
public static void main(String []args){
Parent p=new Parent();
Class c= p.getClass();
Child child =new Child();
Class c1= child.getClass();
System.out.println(c.getSuperclass());
System.out.println(c1.getSuperclass());
}
You will get output as :
class java.lang.Object
class Parent
Option 2, as every object derives Object.class methods
The right answer is Option 2. Any Java class inherit all parents for their parents. In other words.
Class A extends Class B
Class B extends Class C
Class C extends Class D
Class X extends A -> it means that A inherit all protected/package/public fields from B,C and D.
In your example, Class Child inherit Parent properties but also Object properties in transitive mode.
From Class Object
public class Object
Class Object is the root of the class hierarchy.
Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
This means that every Java class has Object as root in the hierarchy, not necessarily as its immediate parent.
No multiple inheritance means in Java a class extends only 1 class; has one immediate base class. Indirectly a class can have many ancestors: Child has Parent and Object as ancestor "super" classes.
Object --> Parent --> Child
--> OtherChild
Relation: 1 --> N
The reason for avoiding multiple inheritance like in C++, was the ambiguity involved:
Pseudo code assuming multiple inheritance:
class A : Comparable
class B : Comparable
class Child : A, B {
#Override A? B?
int compareTo(Child rhs) { ... super.compareTo ? ... }
}
A a = new Child();
B b = new Child();
a.compareTo(b);
First of all, using Java 8, it is possible to accomplish Multiple inheritance using Default methods of interfaces.
Secondly, your understanding regarding Object class is correctly represented in 'Option 2'.
However, it is not multiple inheritance, rather multilevel inheritance. 'Option 1' is multiple inheritance.
Please check this link to read more about them.
option 2.Object is a superclass of all other classes,but Object may not a dirrect superclass of a classe.

Mocking abstract super class method directly from child class

I have a sub class that extends abstract class called AbstractParentClass
like
class Child extends AbstractParentClass
This AbstractParentClass contains a method called getParentAbstractServiceMethod which returns some service class object. That services class has another method called getParentAbstractClassDomainFacade which returns some other class object which is not abstract and so on...This is like method chaining.
Snippet inside Child class is as follows
SessionClass userSession = (SessionClass)
getParentAbstractServiceMethod().getParentAbstractClassDomainFacade().getParentAbstractClassDomainObject(SessionClass.NAME);
How to mock getParentAbstractServiceMethod() method since this is abstract class method I cannot instantiate it and call..
The best solution was to follow the "Favour composition over Inheritance" principle and turn the AbstractServiceClass into a regular class that gets the current extenders as dependencies implementing an interface that provides the method to be called on them.
having written this the less advisable solution is to create a mock of the Abstract class using Mockito:
AbstractParentClass cut= Mockito.mock(AbstractParentClass.class,Mockito.CALLS_REAL_METHODS);
Mockito.when(cut.getParentAbstractServiceMethod()).thenAnswer(...);
I think you should step back and look at your design. What is the point of testing a child class (of an abstract class) ... that doesn't implement the abstract methods in the first place.
I think you should do the following:
A) test your base class as far as possible; for example by creating a test only child class that somehow meaningfully implements the abstract methods
B) make sure that your "real" child classes provide reasonable implementations of your abstract methods.
And hint: consider not putting abstract into your method names. They are only abstract on the parent level; not in the childs that implement them.

Make only child class able to call constructor in java

I want to extend a class A and call the constructor of the class A from the child class B with the super() method. Also should the class A only be instantiated via the child class B. I can do that very simply by making class A abstract. But I read that I should only declare classes abstract, when they have at least one abstract method. Is there another way of making class A only be instantiated by the child class B by calling the super() method?
You should use abstract if there are certain implementations your child class needs, especially if you don't want the parent class to be instantiated ever!
However, in your case, I don't think there are any methods that need to be implemented or inherited, so you can just use protected.
Good luck!

Is there any way to access child object's variable when the object is referred by its super class?

Is there any other way to access child object's variable when the object is referred by its parent class other than casting the object to child class?
class parent{
int parentData;
}
class child extends parent{
int childData;
}
parent obj =new child();
obj.childData =10 ; //is getting error
((child )obj).childData=10; // is working fine
is there any other way to access child class variable where child class object is pointed by parent class ?
scenario
If my parent class has 2-3 child class that are differ with parent class by only one variable and i tried to refer all child class object with parent class.In some point i need to get child variable what should i do ? do i need to redesign ?
The parent class should contain only behavior that is common to all child classes.
If what you are trying to implement in the parent class is indeed common behavior you might want to look in to the Template method pattern.
If what you are implementing is different behavior over the child classes, do not try to shoehorn it into the parent class but implement it in the child classes. If these implementations share common parts, you could extract this to a common method either in the parent or a helper class.
How come parents started to know thier childs in java? That's not possible.

Proper (Java) convention to access ancestor and parent methods?

What's the proper convention to access ancestor and parent methods from down an inheritance chain?
For example, methodA() resides in the base ancestor class and methodB() resides in the parent class. If I'm in a child/subclass that extends parent (which in turn extended the ancestor/base class), what is the proper way to access methodA()?
Obviously super.super.methodA() is not allowed.
What does work is super.methodA(), this.methodA() and simply calling methodA() on it's own.
Which of the above three cases is the 'correct' way to call methodA() that resides in the ancestor class?
If methodA() is defined only in the grandparent class, and isn't overridden in the parent class or child class, then simply calling methodA() in the child class will correctly call the inherited method.
Accessing a classes grandparent methods is not allowed. See Why is super.super.method(); not allowed in Java? form more information.

Categories