Why is the parent class method called? - java

Why is the parent class method called when I am creating a child object. This is not even a static method.
class Parent {
public String pubMethod(Integer i) {
return "p";
}
}
public class Child extends Parent {
public String pubMethod(int i) {
return "c";
}
public static void main(String[] args) {
Parent u = new Child();
System.out.println(u.pubMethod(1)); // Prints "p" why??
}
}
Here I am passing a primitive int . Still it goes to the parent method.
Any explanation?

When you call u.pubMethod(1), the compiler considers only the signatures of the methods of Parent class, since Parent is the compile-type type of u. Since public String pubMethod(Integer i) is the only method of Parent having the required name, that's the selected method. public String pubMethod(int i) of Child class is not considered as a candidate, since Parent has no method of such signature.
In run-time, the method of the sub-class, public String pubMethod(int i), cannot override the super-class method public String pubMethod(Integer i), since it has a different signature. Therefore the Parent class method is executed.
In order for the Child class to be executed, you must either change its signature to match the Parent class method's signature, which will allow it to override the Parent class method:
public class Child extends Parent {
#Override
public String pubMethod(Integer i) {
return "c";
}
}
Or you can add a second method to the Parent class, which the existing Child class method will override:
class Parent {
public String pubMethod(Integer i) {
return "pInteger";
}
public String pubMethod(int i) {
return "pint";
}
}
In the first case, the compiler will still have a single method to choose - public String pubMethod(Integer i) - but in run-time the Child class method will override it.
In the second case, the compiler will have two methods to choose from. It will choose public String pubMethod(int i), since the type of the literal 1 is int. In run-time, the Child class public String pubMethod(int i) method will override it.

I think you didnt create your child object properly, you have:
Parent child = new Child();
But you should have:
Child child = new Child();

Related

child class object in unable to run overridden method instead parent class method is being run both times

new to programming...just trying to understand method overriding.
In the following code, object from child class which overrides Parents class method, but still with child class object I can't run overridden method (m()).
I set return type different-- float in parent and double in child, if the particular method is not overridden due to that then child class also implements the same method from interface u and still not running overridden method..
class Parent {
public float m(float m){
System.out.println(" parent class with float return");
return m;
}}
class Child extends Parent implements u {
#Override
public double m(double y) { /*method name same - Parent class & interface
different return type */
System.out.println(" child class with double");
return y;
}
public static void main(String[] args) {
Child child = new Child();
child.m(10);/*child object running parent method*/
Parent g = new Child();
g.m(10);
}
}
interface u {double m(double y);}
You are trying to override a method called m which returns a double which doesn't exist in the parent class, the parent class has a method m with a return type of float, these are different. Basically the current #Override doesn't actually override anything since a method with that name and return type doesn't exist in the parent.
You fulfil the interface contract because a method m exists which returns a double.
The reason why you get the same output is because you are calling the Parent classes m function because of the type of argument you are passing in (10 is being determined as a float). If instead you call the function with a double, i.e 10d then the Child classes m method will be called.
Change your main method to the following and it will now call the parent and child methods:
public static void main(String[] args) {
Child child = new Child();
child.m(10.0);/*child object running parent method*/
Parent g = new Child();
g.m(10);
}

Is overloading in inheritance class possible in Java?

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

instanceof, subclasses and casting

if I have a class myClass1 and a second class myClass1Extended that is an extension of the first class, I have this source code:
myClass1 c1 = something(); // line 1
myClass1Extended c1ex = somethingElse(); // line 2
if (c1ex instanceof myClass1) { // line 3
(myClass1)c1ex.doSomething(); // line 4
}
I have a few questions:
in Line 3, will the operator instanceof return true?
in line 4, supposing the first answer is yes, what will happen if doSomething() has not been overriden in myClass1Extended?
And what happens instead if doSomething() has been overriden?
in line 4, is (myClass1) necessary?
Thank you very much
Why don''t you try the code to see?
yes
it will call the one in the parent class
it will call the one in the child class
no.
Given:
class Parent
{
public void foo()
{
System.out.ptintln("parent::foo");
bar();
}
public void bar()
{
System.out.println("parent::bar");
}
}
class Child
extends Parent
{
public void foo()
{
super.foo();
System.out.ptintln("child::foo");
}
}
You can use the Child class anywhere you use the Parent class, because all Children are types of Parents.
When the compiler looks at this code:
Parent p = new Child();
it verifies that the Child extends or implements the Parent.
When the compiler looks at this code:
p.foo();
it verifies that the type the p is declared as, Parent, has a foo method.
At runtime when the p.foo() line is executed the Virtual Machine looks at the type that p is actually pointing at, Child, and looks there for the foo method. Assuming the foo method is found in Child it runs it, otherwise it looks at the Parent class for it.
In the Parent class when the foo method calls bar the compiler again looks to make sure that the Parent class has a bar method. At runtime the VM again looks at the Child class to for the bar method, and since it does not it calls the one in the Parent.
If the methods don't exist in Parent then they have to exist the in the parent class of Parent, all the way up to java.lang.Object.
To answer your question take this example here:
package test;
public class Parent
{
public void printFoo()
{
System.out.println("foo");
}
public void printBar()
{
System.out.println("bar");
}
}
package test;
public class Child extends Parent
{
#Override
public void printFoo()
{
System.out.println("myFoo");
}
}
package test;
public class Main
{
public static void main(String ... args)
{
Parent test = new Child();
Parent test2 = new Parent();
print(test);
print(test2);
}
public static void print(Parent parent)
{
if (parent instanceof Parent)
{
System.out.println(parent.getClass().getName()+" is Parent");
parent.printFoo();
parent.printBar();
}
}
}
As you can see Child inherits from Parent and overrides printFoo() method. On printing those Parent objects you will get the following output:
test.Child is Parent
myFoo
bar
test.Parent is Parent
foo
bar
So to answer your questions:
1) yes
2) it will call the method of the parent class
3) it will invoke the overriden method - if this method contains a super-call then the parent's method will execute as well
4) No - if you specify f.e. Parent o = new Child() and implement a method in Child that is not present in Parent and you want to invoke the method of the child object, you will have to cast it back to Child ((Child)o).invokeYourMethod()

Can a parent class call the method of a grandchild class?

I have a main method in my overall parent class, outside of that main method I have two other methods that I will call inside the main method. Each of these outside methods call a method that was defined in, not the child, but the grandchild class.
Here is where I get really confused. In my big parent class, the two methods that aren't the main method take in an array that is the type of the child class. This is because each item in the array is a different type the grandchild classes. I get that because the methods that I'm calling in the parent class aren't defined in the child class (they are defined in the grandchild class) that is why they cannot be called. Is there a way to typecast the indexes to each individual grandchild class type in a for loop in the array? Or any other way?
Sorry if this is a super confusing way to phrase this question.
The normal way to do this is for the parent class to be declared abstract, and to declare that the method should exist. The grandchild class will supply a version of the method. For example:
public abstract class Doubler {
int a;
public Doubler(int a) {
this.a = a;
}
abstract int modifyResult(int aResult);
int calculate() {
int rv = a * 2;
return modifyResult(rv);
}
}
public class DoublerAndAdder extends Doubler {
int b;
public DoublerAndAdder(int a, int b) {
super(a);
this.b = b;
}
#Override
public int modifyResult(int aResult) {
return aResult + b;
}
}
calculate() is allowed to call modifyResult() even though modifyResult() is declared abstract and there is no implementation. Calling DoublerAndAdder.calculate() will run Doubler.calculate(), which will call DoublerAndAdder.modifyResult().
If you can't make the parent class abstract, the parent class can provide a version of the method which doesn't do anything:
public abstract class Doubler {
int a;
public Doubler(int a) {
this.a = a;
}
public int modifyResult(int aResult) {
return aResult;
}
int calculate() {
int rv = a * 2;
return modifyResult(rv);
}
}

Create a parent class that returns child class objects

I'm building a base/parent class in Java that's going to have several methods for creating the class itself and I'm wondering if there's any way to have the parent class return instances of the child class instead of returning instances of the parent class that then have to be cast to the child?
For example, here's my parent class:
public abstract class SFObject
{
// Variables
protected String mID;
protected String mName;
// Function called to create ourselves from a DiffObject
public abstract SFObject CreateFromDiffObject(DiffObject object);
// Function called to create a list of ourselves from a query
public List<SFObject> CreateListFromQuery(Connection connection, String query)
{
// Run the query and loop through the results
ArrayList<SFObject> objects = new ArrayList<SFObject>();
for (DiffObject object : connection.Query(query))
objects.add(CreateFromDiffObject(object));
return objects;
}
}
If I create a child class based on my SFObject class, the two functions in my child class will still return an SFObject (that needs to be cast to my child class type) or a list of SFObjects (that need to be individually cast to my child class type). Is there any way (maybe using Reflections) to have my child class returns instances of itself as itself and not as SFObjects?
What you are describing is known as a covariant return type.
Class A {
A getInstance() { ... }
}
Class B extends A {
#Override
B getInstance() { ... }
}
This has been allowed since Java 1.5.
If you place the child class object inside of the parent object, methods called will run from the child class. But it will look like the parent object on the surface
public class A{
method 1(){//do some stuff}
method 2(){//do some stuff}
}
public class B extends A{
method 1(){super.method 1()
//do some other stuff}
method 2(){super.method 2()
//do some other stuff}
}
public class test{
A a = new B();
//any method called on 'a' will come from the child class
// But 'a' is the parent object
}
Not sure if I really understand your Problem correct because it sounds to me lke this:
class p
{
public static p createParent()
{
return new p();
}
public static c createChild()
{
return new c();
}
}
Of course it doesn't have to be static, just thought of some kind of factory.
Exactly for this functionalities are proposed the factory methods, as you already implemented. In the child class you can change the return type without offending the method declaration. A sample for your case would be something like:
public abstract class SFObject {
// Variables
protected String mID;
protected String mName;
// Function called to create ourselves from a DiffObject
public abstract SFObject CreateFromDiffObject(DiffObject object);
// Function called to create a list of ourselves from a query
public List<? extends SFObject> CreateListFromQuery(Connection connection, String query) {
// Run the query and loop through the results
ArrayList<SFObject> objects = new ArrayList<SFObject>();
for (DiffObject object : connection.Query(query))
objects.add(CreateFromDiffObject(object));
return objects;
}
}
class SFObjectChild extends SFObject {
#Override
public SFObjectChild CreateFromDiffObject(DiffObject object) {
SFObjectChild result = new SFObjectChild();
//...
return result;
}
#Override
public List<? extends SFObjectChild> CreateListFromQuery(Connection connection,
String query) {
return null;//..;
}
}
This is acceptable because the return type of the children class is still a kind of (hierarchical speaking) the parent.
Be aware of java code conventions (methods in camel case starting with low, e.g. createFromDiffObject).

Categories