I have below parent class :-
class Parent {
Parent() {
System.out.print("Parent ");
}
}
class Child extends Parent {
Child() {
System.out.print("Child");
}
}
So when i execute Child c = new Child();
My output should be "Child" Not "Parent Child"
can we do that using reflection API?
Requirement :-
I have a long Junit Setup hierarchy Which I want to avoid for some of the classes
What happens is when you create the Child class the Parent's class constructor is called first and then the Child's constructor.
What you could do if you must change what happens in the parent constructor is that you extract the related code into a protected method and this way you can override it in the Child class
However it is error prone and not recommended (What's wrong with overridable method calls in constructors?)
class Parent {
Parent() {
overridableInit();
}
protected void overridableInit() {
System.out.print("Parent ");
}
}
//If you want to extend the behavior:
class Child1 extends Parent {
#Override
protected void overridableInit() {
super.overridableInit();
System.out.print("Child1 ");
}
}
//If you want to skip the Parent behavior:
class Child2 extends Parent {
#Override
protected void overridableInit() {
System.out.print("Child2 ");
}
}
Related
Suppose I have this hierarchy of classes
class Parent {
protected List<Object> things = new List<Object>;
public Parent() {
things.addAll(declareThings());
}
public List<Object> declareThings() {
// things declaration
}
}
class Child extends Parent {
public List<Object> declareThings() {
// additional things declaration
}
}
class GrandChild extends Child {
public List<Object> declarThings() {
// addtional things
}
}
I would like that creating an instance of say GrandChild, I get all the declared things in the hierarchy. Is it possible to implement such behaviour?
For each subclass, add a constructor where the first instruction is super();.
Is overloading in inheritance class possible in Java? Parent class and Child class contain the same method name, but different parameters. Is this overloading?
class Parent {
public void add(int a) {
System.out.println("I am parent" + a);
}
}
class Child extends Parent {
public void add(long a) {
System.out.println("I am child.");
}
}
Yes. While extending any class, internally it means all accessible behaviour of the parent class will be present or inherited in child class. i.e, so in your case same name with different argument is overloading.
Yes of course, overloading in inheritance class is possible in Java. Java compiler detect that add method has multiple implementations. so according to the parameter java compiler will determines which method has to be executed.
class Parent {
public void add(int a) {
System.out.println("I am parent " + a);
}
}
class Child extends Parent {
public void add(long a) {
System.out.println("I am child.");
}
}
class Demo{
public static void main(String args[]){
Child child = new Child();
child.add(1); // prints "I am parent 1"
child.add(1L); // prints "I am child."
}
}
Yes, In java allow overloading concept which means you can declare different method with Same name and different parameter .In your case You are extending the parent class ,which means all the property of parent class available in child class(child).
Its a overloading:
Child c = new Child();
c.add(1);//it will call the parent method
c.add(1L);//It will call the child method
The following is a popular use case involving abstract method and overridding.
class Demo {
public static void main(String[] args) {
Parent a = new Child_A();
Parent b = new Child_B();
a.method();
b.method();
}
}
abstract class Parent {
abstract void method();
}
class Child_A extends Parent {
#override
void method() {
do the task for Child_A;
}
}
class Child_B extends Parent {
#override
void method() {
do the task for Child_B;
}
}
It seems that we can always achieve the same thing by defining a generic method in the superclass, which uses the instanceof keyword to determine the subclass and performs the corresponding task for the subclass.
class Demo {
public static void main(String[] args) {
Parent a = new Child_A();
Parent b = new Child_B();
a.method();
b.method();
}
}
class Parent {
void method() {
if (this instanceof Child_A) {
do the task for Child_A;
}
else if (this instanceof Child_B) {
do the task for Child_B;
}
}
}
class Child_A extends Parent {
}
class Child_B extends Parent {
}
Which code style is better and why?
Because:
you don't want to have to modify the parent class every time you add another subclass
in some circumstances like a library API you may not even know all the subclasses
code that deals with a subclass should be in that subclass, not in the parent.
If you do the latter, your subclasses becomes useless. They don't do anything. I'd like to think of it this way, the parent passed you the ability to do methodA in your own way. However in your case, the parent does everything, meaning you are dependent on your parent forever. Who would want that?
Well aside from that, when you create a new subtype, you'll have to edit also the parent(very absurd), think of what will happen 100 subtypes later. Give your subtypes the power to have their own individuality.
As per this question, while I understand why it goes wrong, how can I effectively solve this while keeping my code DRY? I wouldn't want to copy and paste the contents in that function into the constructor.
Suppose I have the following
class Parent
{
Parent()
{
overridableFunction();
}
void overridableFunction()
{ ... }
}
class Child extends Parent
{
Child()
{
super();
overridableFunction()
}
void overridableFunction()
{ ... // overridden }
}
Ideally, I wish the execution flow of the Child constructor to be
Parent() --> Parent.overridableFunction() --> Child.overridableFunction()
How can I achieve this without copying and pasting stuff around thus making the code WET?
If you wish Parent's constructor to execute its own implementation of overridableFunction() and Child's constructor to execute its own implementation of overridableFunction(), what you are basically saying is you don't want Child's overridableFunction() to override Parent's overridableFunction() method.
You can give the two methods different names, or keep the names identical, but make Parent's method private, to avoid any overriding.
I am not sure why you want to do it, but this follows the execution flow you asked for :
class Parent
{
Parent()
{
overridableFunction();
}
void overridableFunction()
{ System.out.println("Parent implementation "); }
public static void main(String[] args) {
new Child();
}
}
class Child extends Parent
{
Child()
{
super();
//remove overridableFunction();
}
#Override
void overridableFunction()
{
super.overridableFunction();
System.out.println("Child implementation ");
}
}
Today I faced a very odd interview question. The interviewer asked me:-
There is a class Parent and it has a method GetData. Class Child1 inherits Parent and Child2 inherits Child1. What you can do in Parent class so that the method "GetData" will be accessible from Child1 but not from Child2?
Kind of a weird setup, but here's another option that works because nested classes can access private members of the outer class:
public class Parent
{
public Parent()
{
GetData();
}
private void GetData()
{
}
public class Child1 : Parent
{
public Child1()
{
GetData();
}
}
}
class Child2 : Parent.Child1
{
public Child2()
{
GetData(); //compiler error, inaccessible due to protection level
}
}
Parent class can mark it's method as private, then declare the first Child inside of it's own declaration.
public class Job
{
private void Test()
{
}
public class JobChild : Job
{
public JobChild()
{
//works
this.Test();
}
}
}
public class JobChildTwo : Job.JobChild
{
public JobChildTwo()
{
//doesn't work
this.Test();
}
}
If we assume that Parent and Child1 exist in Assembly A while Child2 exists in Assembly B, and Assembly A does not expose its internals to Assembly B whilst Assembly B references Assembly A, then you can mark GetData as internal, at which point it will be accessible to Child1 but not Child2.
The side effect here is that it would be visible to the entire assembly.
Note that protected internal would have the opposite effect - it would make GetData visible to child2, since protected internal is explicitly "protected OR internal" as per MSDN