Saturday, January 26, 2013

1/26/13 Inheritance

Sometimes you are coding something using multiple classes, and you find yourself writing the same code for each of those classes. Did you know that you can make one class inherit methods and variables from another? This will allow you to create a class that contains everything that another class dose plus more! To make one class Inherit another, you would type the following after the class name and before the open brace:
extends supperclass
where supperclass is the class that you want to inherit. This will give your class access to all the methods in supperclass as well as giving a copy of all of the private variables that you can find in supperclass. If you want to run a constructor for supperclass inside of your class, you can just type:
supper(arguments);
Is this still confusing? If so, I will give you and example:
public class one{
 private int number;
 private boolean isTrue;

 public one(){
  number=0;
  isTrue=false;
 }

 public one(int num, boolean truth){
  number=num;
  isTrue=truth;
 }

 public int test(int i){
  if(isTrue){
   return number*i;
  }
  return number/i;
 }
}

public class two extends one{
 private string word;

 public two(){
  supper();
  word = "";
 }
 public two(int num, boolean truth, String str){
  supper(num, truth);
  word = str;
 }
 public int run(){
  return test(word.length);
 }
}

This code here is a very basic example for how to create a class that inherits another. As you can tell, this can be used to do a lot of things. If you do not fully understand what the relationship is between a supper and sub class, you can think of it like cars. A Honda accord would be a sub class of Honda, which in turn is a sub class of car. This would make Honda a supper class of the Honda accord and car a supper class of Honda. As this may infer, you can have two or more sub classes for one supper class. As always, I hope you learned a thing or two about Inheritance and java.

No comments:

Post a Comment