0

I have created a class Check as a parent class and define one method as a static and also one more class Check1 that extends Check class now I created a object of class Check1 and call the Check class method with this object and its work properly. How can it would be possible ? because static method of class work only with the name of class .

Check class:

public class Check
{
  static void main(int a[])
  {
    for(int i=0; i<a.length; i++)
    {
        System.out.print(a[i] + "\t");
    }   System.out.println();
  }
}

Check1 class:

public class Check1 extends Check
 {

public static void main(String a[])
{
    Check1 ob=new Check1();
    int a1[]={1,2,3,4};
    ob.main(a1);                    // working
    main(a1);                      // working
    Check.main(a1);                 // working
    Check1.main(a1);                // working
    System.out.println("Main");
}
}

give me a solution or am I doing wrong in my program?

Manoj Gupta
  • 298
  • 1
  • 4
  • 20
  • You can also do it with null object because static method checks class not object such as `Check c=null; c.main(a1);`. There is no null pointer exception in this case. – Braj Mar 08 '14 at 06:20
  • It's not clear what you're trying to do, or even what's not working. But your object has the same name as your class, so an object method call would look exactly like a static call. – BarryDevSF Mar 08 '14 at 06:21
  • You are overriding the `main()` method. You don't always have to put the name of the class in front. You can also just call it by name from within the class. I'm pretty sure when you use `Check1.main()` you will get a stack overflow, because you are causing infinite recursion! – Chloe Mar 08 '14 at 06:34
  • This may help you..http://stackoverflow.com/questions/10291949/are-static-methods-inherited-in-java – Nikunj Panelia Mar 08 '14 at 07:35

2 Answers2

0

static methods are inherited just like any other method, and can be overridden just like any other method. static simply implies that the method isn't bound to an instance of a class, but the class itself.

aruisdante
  • 8,875
  • 2
  • 30
  • 37
0

I hope when you see this example you will understand about static

public class Animal
{
    public static void hide() 
    {
        System.out.format("The hide method in Animal.%n");
    }
    public void override()
    {
        System.out.format("The override method in Animal.%n");
    }
}

public class Dog extends Animal
{
    public static void hide() 
    {
        System.out.format("The hide method in Animal.%n");
    }
    public void override()
    {
        System.out.format("The override method in Animal.%n");
    }
   public static void main(String args[])
   {
     Animal a = new Dog();
     a.hide();
     a.override();
   }
}

In simpler terms, instance methods are overridden and static methods are hidden.

Thank you.

T8Z
  • 691
  • 7
  • 17