RSS

Three OOP Concepts Coding Example: Part #2 (Inheritance)

09 Oct

This article will be showing coding example of Inheritance, one of the three Object Oriented Programming Concepts. If you still do not know what Inheritance is, I recommend to read my previous article.
You may not want to write same code again and again to the new class, this is not a good practice either. One of the major advantages of Inheritance is to reduce the duplicate coding. So the application becomes more flexible. This is another power of Object Oriented Programming.
Accessing Type: public, private, protected
You can access one variable/ methods from another class using Inheritance mechanism. Before discussing that I want to discuss about Java’s some accessing types i.e. public, private, protected. These are basic accessing types:
• Public: If you declare one variable public that means you can access that variable from any where from that class or from other class (if you extends that class).
• Private: If you declare one variable / method private that means that member can only be accessed by other member of it’s class.
• Protected It appers only when inheritance is at the place.
Let’s move on the coding. Assume you have two classes namely Test1 and Test2. If you want to inherit class Test1 into Test2 you have to use extends keyword in Java.
 

/*@author: Md. Golam Rabbi
* Test1.java
*/
public class Test1 {
public String pubString = "This string is made public";
private String pvtString = "This string is made private";
String string = "This is a string";

public void pubMethod() {
System.out.println(pubString);
}

private void pvtMethod(){
System.out.println(pvtString);
}

public void defaultMethod(){
System.out.println(string);
}
}

Now Test2.java :

public class Test2 extends Test1{

public Test2() {
pubMethod();
defaultMethod();
}

public static void main(String args[]){
new Test2();
}

}


If you run Test2.java file you will see this result:
This string is made public
This is a string
Now you see you can not access those member of the class who are made private from another class. But when you inherit a class you get all the properties of that class. Also you can inherit only one class at a time.

 
Leave a comment

Posted by on October 9, 2012 in Java

 

Tags: , ,

Leave a comment