• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 163
  • Last Modified:

static method overriding vs normal non static method overriding in child class

Hi,

How static method overriding vs normal non static method overriding in child class are different?. child Static method overriding hides parent class static method right which is same with non static methods also right? When we use each one. Please advise

public class Parent {
    public static void test() {
        System.out.println("test from Parent class");
    }
}

public class Child extends Parent {
    public static void test() {
        System.out.println("test from Child");
    }
}


now non static case as below

public class Parent {
    public void test() {//non static
        System.out.println("test from Parent class of nonstatic");
    }
}

public class Child extends Parent {
    public  void test() {//non static
        System.out.println("test from Child of nonstatic");
    }
}
0
gudii9
Asked:
gudii9
  • 9
  • 3
2 Solutions
 
Jeffrey Dake Senior Director of TechnologyCommented:
Static methods are mot really overridden but rather hidden. Since you make a call to static methods through the class, you can still call the static method in the base class by referencing it

Parent.test() vs  Child.test()

Both will work and call the static function declared in the classes.

However when you have a regular method. The method being called will be whichever the class implements.

Here is a good description. https://docs.oracle.com/javase/tutorial/java/IandI/override.html
0
 
gudii9Author Commented:
public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

The Cat class overrides the instance method in Animal and hides the static method in Animal. The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The static method in Animal
The instance method in Cat


Cat myCat = new Cat();
        Animal myAnimal = myCat;

as above after creating cat object(myCat) why they are assigning to Animal instance ie myAnimal
0
 
gudii9Author Commented:
package com.upcast;

public class Cat extends Animal {
	public static void testClassMethod() {
		System.out.println("The static method in Cat");
	}

	public void testInstanceMethod() {
		System.out.println("The instance method in Cat");
	}

	public static void main(String[] args) {
		Cat myCat = new Cat();
		Animal myAnimal = myCat;
		myAnimal.testClassMethod();
		myAnimal.testInstanceMethod();
	}
}

Open in new window


i changed
Animal.testClassMethod();
to
myAnimal.testClassMethod();

still got same output as
The static method in Animal
The instance method in Cat


what is exact meaning of hiding? i did not get that. i understood oerriding part of parent method with child method which dominates
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Jan LouwerensSoftware EngineerCommented:
The non-static cases is the concept of Polymorphism. The actual method called is based on the actual type of the object on which the method is called.

Static methods do not have an associated object. The correct version needs to be explicitly called:
Animal.testClassMethod();
// vs
Cat.testClassMethod();

Open in new window


This type of code is confusing, and should generate a warning in the compiler:
Animal myAnimal = myCat;
myAnimal.testClassMethod();   // this line should generate a compiler warning, since a static method is being called on an object, rather than explicitly stating which version is intended

Open in new window

0
 
gudii9Author Commented:

This type of code is confusing, and should generate a warning in the compiler:

i see warning but it does work though giving below output

The static method in Animal
0
 
gudii9Author Commented:
what is it exactly hiding here? why it is called hiding?

Cat myCat = new Cat();        

 Animal myAnimal = myCat;

as above after creating cat object(myCat) why they are assigning to Animal instance ie myAnimal??
0
 
gudii9Author Commented:
when i try this example getting error
http://crunchify.com/java-method-hiding-and-overriding-override-static-method-in-java/

package com.solution;

import com.upcast.Company;

/**
 * @author Crunchify.com
 */
 
public class CrunchifyHideStaticMethod {
	public static void main(String args[]) {
		Company cmp = new CrunchifyCompany();
		// if we can override static, this should call method from Child class
		cmp.staticMethod(); // Eclipse should show warning: The static method
							// staticMethod() from the type Company should be
							// accessed in a static way
		cmp.nonStaticMethod();
	}
}
 

Open in new window


package com.solution;
// CrunchifyCompany: Sub-Child Class
class CrunchifyCompany extends Company {
	/*
	 * static method of same name and method signature as existed in super
	 * class, this is not method overriding instead this is called method hiding
	 * in Java
	 */
	public static void staticMethod() {
		System.err.println("CrunchifyCompany: Overridden Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("CrunchifyCompany: non-Static method");
	}
}

Open in new window


package com.solution;
// Comapny: Super-Parent Class
class Company {
 
	// public static method which can not be overridden in Java
	public static void staticMethod() {
		System.out.println("Company: Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("Company: non-Static method");
	}
}
 

Open in new window


package com.solution;

public class CohesionExampleProblemSolution {
}

class InternetDownloader {
	void downloadFromInternet() {

	}

	class DataParser {
		void parseData(String content) {

		}
	}

	class DatabaseStorer {

		void storeIntoDatabase(String data) {

		}
	}

	void doEverything() {
		new InternetDownloader().downloadFromInternet();
		new DataParser().parseData();
		new DatabaseStorer().storeIntoDatabase();

	}
}
/*
 * public class CohesionExampleProblem{
 * 
 * }
 */

Open in new window


my error is'

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
      Type mismatch: cannot convert from CrunchifyCompany to Company
      The method staticMethod() is undefined for the type Company
      The method nonStaticMethod() is undefined for the type Company

      at com.solution.CrunchifyHideStaticMethod.main(CrunchifyHideStaticMethod.java:11)



please advise
0
 
Jeffrey Dake Senior Director of TechnologyCommented:
Looks like you are importing a different Company class. Your example creates a class Company in the com.solution package, however in your CrunchifyHideStaticMethod class you are importing com.upcast.Company. This is a different class with the same name which is why you get the error.
0
 
gudii9Author Commented:
it got resolved.

I wonder why we got below output

Company: Static Instance method
CrunchifyCompany: non-Static method


i expected as below?

CrunchifyCompany: Overridden Static Instance method
CrunchifyCompany: non-Static method

please advise
0
 
gudii9Author Commented:
package com.solution;

import com.solution.Company;

/**
 * @author Crunchify.com
 */
 
public class CrunchifyHideStaticMethod {
	public static void main(String args[]) {
		Company cmp = new CrunchifyCompany();
		// if we can override static, this should call method from Child class
		cmp.staticMethod(); // Eclipse should show warning: The static method
							// staticMethod() from the type Company should be
							// accessed in a static way
		cmp.nonStaticMethod();
	}
}
 

Open in new window


package com.solution;
// CrunchifyCompany: Sub-Child Class
class CrunchifyCompany extends Company {
	/*
	 * static method of same name and method signature as existed in super
	 * class, this is not method overriding instead this is called method hiding
	 * in Java
	 */
	public static void staticMethod() {
		System.err.println("CrunchifyCompany: Overridden Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("CrunchifyCompany: non-Static method");
	}
}

Open in new window


package com.solution;
// Comapny: Super-Parent Class
class Company {
 
	// public static method which can not be overridden in Java
	public static void staticMethod() {
		System.out.println("Company: Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("Company: non-Static method");
		System.out.println("test commit in git");
	}
}
 

Open in new window


package com.solution;

public class CohesionExampleProblemSolution {
}

class InternetDownloader {
	void downloadFromInternet() {

	}

	class DataParser {
		void parseData(String content) {

		}
	}

	class DatabaseStorer {

		void storeIntoDatabase(String data) {

		}
	}

	void doEverything() {
		new InternetDownloader().downloadFromInternet();
		new DataParser().parseData();
		new DatabaseStorer().storeIntoDatabase();

	}
}
/*
 * public class CohesionExampleProblem{
 * 
 * }
 */

Open in new window

0
 
Jeffrey Dake Senior Director of TechnologyCommented:
This is why it is not recommended to call a static method via an object. Since that reference was typed as a Company it calls that method. Most editors, like eclipse will give you a warning. You really should call static methods directly like Company.staticMethod();
0
 
gudii9Author Commented:
cmp.staticMethod(); // Eclipse should show warning: The static method
                                          // staticMethod() from the type Company should be
                                          // accessed in a static way
            cmp.nonStaticMethod();


so i modified as below to make compiler happy


company.staticMethod(); // Eclipse should show warning: The static method
                                          // staticMethod() from the type Company should be
                                          // accessed in a static way
            cmp.nonStaticMethod();


to conclude:

so method call is happened generally based on the reference type right  but in case of non static overridden method it happens instead of reference type based on actual object type right?

but in case of  static overridden method it happens instead of reference type best to use class name  and call is based on actual classobject type right even though method seems like overrident but it is not but just hiding there ?
0
 
gudii9Author Commented:
https://docs.oracle.com/javase/tutorial/java/IandI/override.html

in above link

The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;//what is the need of this step. why assigning mycat to myAnimal. it makes no sense to me????
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}
The Cat class overrides the instance method in Animal and hides the static method in Animal. The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The static method in Animal
The instance method in Cat
As promised, the version of the hidden
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 9
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now