Solved

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

Posted on 2016-08-15
13
88 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
  • 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
 
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

863 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now