This section descibes about inheritance in java.
Introduction to inheritance
Inheritance is the relationship among classes, in which one class can use the structure or behavior of one or more classes. The class which inherit the property of another class is known as "subclass" and the class who shares it's structure and behavior is called as "super class".
For inheriting property of one class into another we use 'extends' keyword as :
class subclass-name extends superclass-name{
// body of class
}
For inheriting the property of a interface into a subclass we use 'implements' keyword as :
public interface University { } public class College implements University{ } public class Department extends College{ }
Note : Java does not support inheritance of multiple superclasses into a single subclass. No class can not extends itself or inherit itself.
Accessibility Restrictions
A subclass can access superclass' public and protected methods and fields but can't access it's private methods. If the classes(subclass and superclass) are in the same package, then you can also access it's default methods and fields.
public class Superclass { public void funtionPublic() { } protected void functionProtected() { } void functionDefault() { } } class Subclass extends Superclass { public void testMethod() { funtionPubli(); functionProtected(); functionDefault(); } }
Method Overriding
If the subclass has same and type signature as a method in superclass, then the method in the subclass is said to override the method in the superclass. And this process is known as method overriding.
Example :
class X { int a, b; X(int i, int j) { a = i; b = j; } // method to display a & b void show() { System.out.println("a and b :" + a + "" + b); } } class Y extends X { int c; Y(int i, int j, int k) { super(i, j); c = k; } void show() { System.out.println("c :" + c); } } public class OverrideDemo { public static void main(String args[]) { Y obj = new Y(1, 2, 3); obj.show();// this method invoke the show() in Y } }
In the above example, class X & Y have same name and type signature. But in main() method, Y class' object is created and with this object show() is called which automatically call show method defined in it's class.
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac OverrideDemo.java C:\Program Files\Java\jdk1.6.0_18\bin>java OverrideDemo c :3 |
[ 0 ] Comments