Static and Inheritance

18 January 2012 By Nithya Vasudevan 261 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • Static members from superclass are not inherited to the sub class.
  • Static methods cannot be overridden in the subclass.
  • Same method can be redefined in the subclass, thus hiding the superclass method
package com.ibytecode.keywords.staticdemo;
class Person
{
	public static void print() { 
		System.out.println("Person");
	}
}
class Student extends Person
{
	public static void print() { 
		System.out.println("Student");
	}
}

public class StaticInheritance {
	public static void main(String[] args) {
		Person[] persons = {new Person(), new Student()};
		for(int i = 0; i<persons.length; i++)
			persons[i].print();
	}
}

Person
Person

We are trying to invoke a static method, persons[i].print(),and the compiler substitutes persons[i] with Person and hence we get Person.print().

Tags: ,