Solved

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

Posted on 2016-08-15
13
130 Views
Last Modified: 2016-08-26
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
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 3
13 Comments
 
LVL 10

Expert Comment

by:Jeffrey Dake
ID: 41757374
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
 
LVL 7

Author Comment

by:gudii9
ID: 41758104
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
 
LVL 7

Author Comment

by:gudii9
ID: 41758436
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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 5

Accepted Solution

by:
Jan Louwerens earned 250 total points
ID: 41758702
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
 
LVL 7

Author Comment

by:gudii9
ID: 41758747

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
 
LVL 7

Author Comment

by:gudii9
ID: 41758748
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
 
LVL 7

Author Comment

by:gudii9
ID: 41763766
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
 
LVL 10

Assisted Solution

by:Jeffrey Dake
Jeffrey Dake earned 250 total points
ID: 41764071
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
 
LVL 7

Author Comment

by:gudii9
ID: 41764414
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
 
LVL 7

Author Comment

by:gudii9
ID: 41764434
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
 
LVL 10

Expert Comment

by:Jeffrey Dake
ID: 41764768
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
 
LVL 7

Author Comment

by:gudii9
ID: 41767217
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
 
LVL 7

Author Comment

by:gudii9
ID: 41767231
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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Suggested Courses

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question