Referring to parent class in Java - java

I want to know if it possible to use This() To reffer MotherClass, Calling My motherClass A and executing it from my Child Class B. witch one is correct ?
Class A { A(){ System.out.println("hello");}
Class B extends A { this() ; B(){System.out.println("World");}}
OR
class A {
Class B { this(); B(){System.out.println("World");} }
}
I want when to Call Class B it show Me (HelloWorld);
Sorry for my bad english.

Calling this() is meaningless unless you are calling it in a constructor and which means to call a constructor overload for this current class (if one exists). Please see this tutorial for the details on this. To call a super class's methods, again use the super keyword.
Incidentally, your code still doesn't compile. Please understand that you can't be careless when coding -- the compiler won't let you, and neither should you be when creating and posting code for questions here.

Create a file - parent.java
public class parent {
parent(){
System.out.println("Hello");
}
}
Create another file - child.java
public class child extends parent {
child(){
super();
System.out.println("World");
}
public static void main(String[] args) {
child c = new child();
}
}
==============================
Creating an instance of child class will first call the parent class constructor and then the child class constructor; resulting in the o/p you are looking for.

Related

Should I use static binding?

I am learning late binding and static binding. Now I am confused about these code.
Here is my analysis:
hello() is non-static method, so we should use the dynamic binding, that is Child.
But there is no hello() method in child class, so go to its super class. Find hello() and print the first line "Hello from parent call calssMethod".
Since the classMethod() is static, so we should use static binding of c, that is also Child. So the output is "classMethod in Child".
So the out put should be
Hello from parent call calssMethod
classMethod in Child
class Parent{
public static void classMethod() {
System.out.println("classMethod in Parent");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Parent");
}
public void hello() {
System.out.println("Hello from parent call calssMethod");
classMethod();
}
}
class Child extends Parent{
public static void classMethod() {
System.out.println("classMethod in Child");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Child");
}
}
public class AA {
public static void main(String[] args) {
Child c = new Child();
c.hello();
}
}
Now, here is the problem. The IDE shows that the output is:
Hello from parent call calssMethod
classMethod in Parent
What's the right analysis process?
What if I make hello() method static?
Class (static) methods aren't overridden as instance methods. When you call the method 'hello()', it will use the method of the parent. When you refer to the class method there, you're referring to the method defined in the class 'Parent'.
Besides that, you should declare your Child instance as 'Parent c = new Child()'. Because you aren't adding new methods to your subclass but rather changing the implementation, you don't lose access to the methods of the subclass. If you were to have to method that returns a Parent object but you return a Child object declared as you did, you'd get problems.
EDIT: To add to this, usually there are 2 reasons to use inheritance: specialisation and extension.
For specialisation, you use define your methods in your superclass and your subclasses differ in how they implement those methods. For example a superclass Animal with subclasses Cat and Dog. 'Animal' has a method makeSound(). You can imagine that both subclasses are going to have a different implementation.
For extension, you use a superclass as a base class containing everything that overlaps. Other than that, the subclasses might have very different implementations and uses. A lot of interfaces have this kind of use.
Whenever we call child class's object, firstly it always find parent class and execute it. As you have static classMethod in both classes so it always run parent's classMethod not child's. You can achieve required answer only by overriding it.
If you make hello() method static even then it will give you same output.

How can we call methods overridden in a java anonymous class?

Consider the code below :
abstract class AbstractClass {
abstract m1();
}
public class Test {
public static void main(String [] args) {
AbstractClass obj = new AbstractClass() {
#Override void m1() {
System.out.print("Instance of abstract class !");
}
};
obj.m1();
}
}
Now here is what I did not understand about this code.
I read that anonymous class creates the class with unknown name which extends the class whose reference is provided (here it is abstract AbstractClass).
Also I remember that we cannot implement the method of child class if the the object is having reference of parent class.
see block of code below
Parent obj = new Child();
obj.methodOfParent();
obj.methodOfChild(); //this gives error
Now here is my point if Anonymous Class extends its Parent Class whose reference is provided, then how can we call overriden methods of Parent Class from Anonymous Class?
I guess you just miss one point. Let me show you example:
class Parent {
public void methodOfParent() {}
public void methodOfParentToBeOverriden() {}
}
class Child extends Parent {
#Override public void methodOfParentToBeOverriden() {}
public void methodOfChild() {}
}
Parent obj = new Child();
obj.methodOfParent(); //this is OK
obj.methodOfParentToBeOverriden(); // this is OK too
obj.methodOfChild(); //this gives error
((Child)obj).methodOfChild(); //this is OK too here.
Please note that when you call obj.methodOfParentToBeOverriden() it will be called implementation from Child class. Independence did you cast this object to Parent type or not.
There is a difference between calling an overridden method of parent and calling a method of child. If a method is declared in class T, you can call it on a variable statically typed as T, regardless of where the method is actually implemented.
In your example, if obj.methodOfParent() happens to be a method override from Child, the method in Child will run, even though obj's static type is Parent.
Same mechanism is in play with anonymous classes: the reason that you are allowed to call obj.m1() is that m1() has been declared in the parent class.

The meaning of 'subclasses of the containing class' in Java?

I came across the expression 'subclasses of the containing class' when I read a paper. What does that containing class mean in Java? This is the excerpt from the paper.
Primarily, this entailed three things: (i) studying the implementation of the entity, as well as its usage, to reason about the intent behind the functionality; (ii) performing static dependency analysis on the entity, and any other types, methods, or fields referenced by it, including constants; and (iii) examining the inheritance hierarchy and subclasses of the containing class. This approach took considerable time and effort to apply.
This example has a subclass of the containing class:
class Parent {
class Child {
}
}
class ParentSubclass extends Parent {
void whatever() {
new Child(); // Creates an instance of Parent.Child
}
}
ParentSubclass is a subclass of the containing class of Child. Note that outside of Parent (or its subclasses), new Child() will not work, as you need to have a containing ("outer") class to instantiate a non-static "inner" class.
Things get a bit crazy when you now add a method doSomething to Parent, invoke it in Child but override it in ParentSubclass.
class Parent {
void doSomething() {
System.out.println("Not doing anything");
}
class Child {
void whatever() {
doSomething(); // actually: Parent.this.doSomething()
}
}
}
class ParentSubclass extends Parent {
void doSomething() {
System.out.println("I'm just slacking.");
}
void whatever() {
Child a = new Child(); // Creates an instance of Parent.Child
a.whatever(); // will print "I'm just slacking".
}
}
Situations like this make static code analysis a quite hard problem.
Since I have no access to the paper, this is my best guess: in Java, classes can be related to each other in more than one way: in addition to inheriting from one another, classes can also be nested inside one another.
Here is an example of a class inheriting from the class inside which it is nested:
public class Outer {
public void doSomething() {
// ...does something
}
private static class Inner extends Outer {
public void doSomething() {
// ...does something else
}
}
}
In the example above, Inner inherits from Outer, which serves as its containing class.

Way to make Java parent class method return object of child class

Is there any elegant way to make Java method located within parent class return object of child class, when this method is called from child class object?
I want to implement this without using additional interfaces and extra methods, and to use this without class casts, auxiliary arguments and so on.
Update:
Sorry that I was not so clear.
I want to implement method chaining, but I have problems with methods of parent class: I lose access to child class methods, when i call parent class methods... I suppose that I'v presented the core of my idea.
So the methods should return this object of this.getClass() class.
If you're just looking for method chaining against a defined subclass, then the following should work:
public class Parent<T> {
public T example() {
System.out.println(this.getClass().getCanonicalName());
return (T)this;
}
}
which could be abstract if you like, then some child objects that specify the generic return type (this means that you can't access childBMethod from ChildA):
public class ChildA extends Parent<ChildA> {
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class ChildB extends Parent<ChildB> {
public ChildB childBMethod() {
return this;
}
}
and then you use it like this
public class Main {
public static void main(String[] args) {
ChildA childA = new ChildA();
ChildB childB = new ChildB();
childA.example().childAMethod().example();
childB.example().childBMethod().example();
}
}
the output will be
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildB
org.example.inheritance.ChildB
What are you trying to achieve ? It sounds like a bad idea. A parent class should not know anything about its children. It seems awfully close to breaking the Liskov Substitution Principle. My feeling is that your use case would be better serve by changing the general design, but hard to say without more informations.
Sorry to sound a bit pedantic, but I get a bit scared when I read such question.
Simply to demonstrate:
public Animal myMethod(){
if(this isinstanceof Animal){
return new Animal();
}
else{
return this.getClass().newInstance();
}
}
You can call this.getClass() to get the runtime class.
However, this is not necessarily the class that called the method (it could be even further down the hierarchy).
And you would need to use reflection to create new instances, which is tricky, because you do not know what kind of constructors the child class has.
return this.getClass().newInstance(); // sometimes works
I know exactly what you mean, in Perl there is the $class variable which means if you call some factory method on a subclass, even if it is not overridden in the subclass, if it instanciates any instances of $class an instance of the subclass will be created.
Smalltalk, Objective-C, many other languages have a similar facility.
Alas, there is no such equivalent facility in Java.
If you are using Kotlin, you can create an extension function
abstract class SuperClass
class SubClass: SuperClass()
fun <T : SuperClass> T.doSomething(): T {
// do something
return this
}
val subClass = SubClass().doSomething()
public class Parent {
public Parent myMethod(){
return this;
}
}
public class Child extends Parent {}
And invoke it like
Parent c = (new Child()).myMethod();
System.out.println(c.getClass());
Is this solution is correct? If it is, then, how is it different from the #1 solution?

calling parent class method from child class object in java

I have a parent class which has a method, in the child class I override that parent class's method. In a third class I make an object of child and by using that object I want call the method of parent class. Is it possible to call that parent class method ? If yes, then how?
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
#Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.
public class Parent {
public int add(int m, int n){
return m+n;
}
}
public class Child extends Parent{
public int add(int m,int n,int o){
return super.add(super.add(m, n),0);
}
}
public class SimpleInheritanceTest {
public static void main(String[] a){
Child child = new Child();
child.add(10, 11);
}
}
The add method in the Child class calls super.add to reuse the addition logic.
First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method.
Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.
Say the hierarchy is C->B->A with A being the base class.
I think there's more to fixing this than renaming a method. That will work but is that a fix?
One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
#Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

Categories