javascript
Brief description  about Online courses   join in Online courses
View Leepika  Mukherjee 's Profile

Simple program on Inheritance

Hi Sir,

Before writing a program on inheritance kindly guide me on how to write a program. There is an example of Car program, but explanation is required about each statement in the program i.e. why the method is written and where is it called, etc...In the course material example of Inheritance is given but its not elaborated.Kindly help me in this.
Asked by Leepika Mukherjee | Feb 1, 2011 |  Reply now
Replies (3)
View sr k 's Profile
Its alright keep posting :)
Feb 13, 2011
View leepika mukherjee 's Profile
Thanks a lot Sir. I was expecting the same and i understood the program easily.
Feb 10, 2011
View sr k 's Profile
Hi

Below is the example that clearly depicts the inheritance concept
i tried my best to present it as simple as possible with comments

below is the code followed by output

//inheritance can be defined as acquiring properties from one class to another class just like a chid inherits some qualities from his parents
//below is the very simple example that demonstrates this concept


public class A {
int a=10;
void somemethod(){
System.out.println("Hi im inside somemethod of class A and class B called me");
}
}
class B extends A{
//class B Constructor
B(){
System.out.println("Hi im in class B Constructor");
}
//in every java program(J2SE) execution starts from main method
//below is the main method where program execution starts
public static void main(String args[]){
//note in the below line small case b is known as object for class B
B b = new B();//creating object for class B and by default this line calls class B Constructor
b.somemethod();//using B's object im calling class A method
System.out.println("now im fetching "+ " a's " +"value which is variable of class A using class B object and its value is "+b.a);
//so this demonstrates inheritance i.e.., acquiring properties from one class to another class
//in the above line im calling variable a using B's object b
//hence this program demonstrates inheritance
}
}

output:
Hi im in class B Constructor
Hi im inside somemethod of class A and class B called me
now im fetching a's value which is variable of class A using class B object and its value is 10
Feb 4, 2011