Aug 19, 2014

19. Inheritance

One class can inherit the functionality of another class. This is important for using frameworks. We just use the subclasses which inherit from the framework classes, rather than writing all the low-level implementations ourselves.




Any class can be a superclass, as long as it does not have the final keyword.


// Ex19.java
package com.javaAndroid.ex19;

public class Ex19 {
 int a,b;
 String s;
 public Ex19 (int a,int b,String s) {
  this.a = a;
  this.b = b;
  this.s = s;
 }
 public void greeting(String gr) {
  System.out.println("Greeting from parent: " + gr);
 }
}



The class Ex19a extends the Ex19, so it inherits everything from the superclass, such as the 3 instance variables. We can then extend it by defining new instance and class variables, constructors and methods. Methods may be overriden, which is the case for the greeting() method. Note, should we not include a super() in the first line of constructor, the compiler will generate an implicit super() call. This will be a problem should we have arguments in the constructors.


// Ex19a.java
package com.javaAndroid.ex19;

public class Ex19a extends Ex19{
 String s1;
 public Ex19a(int a, int b, String s, String s1) {
  super(a,b,s); // calling superclass constructor
  this.s1 = s1;
 }
 @Override  // optional, compiler checks if super has same signature
 public void greeting(String gr) {
  System.out.println("Greeting from the child: " + gr);
  super.greeting(gr);
 }
}



The class Ex19b has the main() method which tests by creating objects of Ex19 and Ex19a classes. The Ex19 object has 3 instance variables, and the Ex19a object has 4 instance variables. In addition, we test the greeting() method. Since, the method is overriden, the child object will only call the child method. Should we want to use the parent method with same name, we have to make an explicit call using super keyword.


// Ex19b.java
package com.javaAndroid.ex19;

public class Ex19b {
 public static void main(String[] args) {
  Ex19 o1 = new Ex19(1,2,"Hello Java");
  System.out.printf("a = %d, b = %d, s = %s\n",
    o1.a,o1.b,o1.s);
  Ex19a o2 = new Ex19a(o1.a,o1.b,o1.s,"Hello Monkey");
  System.out.printf("a = %d, b = %d, s = %s, s1 = %s\n",
    o2.a,o2.b,o2.s,o2.s1);
  String str = "Java!";
  o1.greeting(str);
  o2.greeting(str); // both greeting() run
 }
}





No comments:

Post a Comment