Thursday, 25 July 2013

Inheritance in JAVA

Inheritance is a process in which a class acquiers the properties as well as behaviour of another class. In this, the class which acquires the properties is called Subclass and the class from which subclass acquires the properties is called Superclass.

Here  Bicycle is a Superclass And all other class is its sub classes  which  inherits the propeties of superclass.

Inheritance can be of 5 types :

1. Single Inheritance
2. Multiple Inheritance
3. Multi-level Inheritance
4. Hierarchial Inheritance
5. Network Inheritance

JAVA doesnot supports Multiple Inheritance. Instead of Multiple Inheritance, it uses another concept termed as Interfacing.
 To inherit the properties we use extends key word. Supposewe have class A and class B.


 public class A
{
.........
........
.......
}
 public class B extends A
{.....
........
......
}

Here class B inherits the properties of A.

example:-

// A simple example of inheritance.
// Create a superclass.

class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

// Create class B  extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[])
 {
A superOb = new A();
B subOb = new B();

superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7; 
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

The output from this program is :
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

Related Posts:

  • Installing JAVA AND Setting CLASS PATH  Installing JAVA AND Setting CLASS PATH        Install jdk 7.4(latest version) or any  other lower                    version.   &… Read More
  • History of JAVA Java is a general-purpose, concurrent, class-based, object-oriented computer programming language that is specifically designed to have as few implementation dependencies as  &nbs… Read More
  • Class in JAVA BASIC All the objects that have similar properties and similar behavior are grouped together to form a class. Class is the java way to implement encapsulation.A class is a user defined data type and objects are the ins… Read More
  • JAVA : Collections                     Collections And Framework                           … Read More
  • Top wesbites to learn Java Wish to create your software games and web applications .Here i suggest some resource for you. Now you habe to practice the things which you read theoretically. It will help to sharp your skills .Apart from us LANG-ADDA the… Read More

0 comments:

Post a Comment