Inheritance in Java
· Inheritance is very important concept
in java
- Java allows you to extends a class with another class
- Is use for sharing between two classes (from parent class to child class)
- extends keyword provide inheritance in java
Example for your understanding
class A // its our base
class or parent class
{
int a=12; //initialization the
value of variable a=2
}
class B extends A // its our
derived class or child class
{
void display() // declaration
of method display
{
System.out.println(+a); // for
print value of a which initialize in claas A
}
}
class demo // main class
{
public static void main(String [] args) // main method
{
B obj=new B(); //create object for class B
obj.display(); //accessing method display
}
}
Firstly remember that
// after this line you can give comment
Anything you written after // is your comment
For that hole line only
Explanation of the above program
Here we take three classes
class A
class B
and class demo its our main class
class A is our parent class
and
class B extends A
means
all properties of patent class A is extended
by the child class B
we declare method display in class B
System.out.println(+a);
Here we want to print the value of
'a'
but value is initialize in class A
we know that by extend keyword
we can access all properties of class A
and we given value of a=12 in class A
hence in above program we get output
12
No comments:
Post a Comment