Monday, December 19, 2016

super keyword use in Java || জাভায় super কিওয়ার্ড ব্যবহার

জাভায় super কিওয়ার্ড ব্যবহার

java super কিওয়ার্ড  ব্যবহার করা হয় parent class এর object .

super কিওয়ার্ড ব্যবহার:
  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.


super is used to refer immediate parent class instance variable

// base class Vahicle
class Vahicle{
int maxspeed = 300;
}
//sub class Car extending vahicle
class Car extends Vahicle{
int maxspeed = 500;
void display(){
// print the max speed of base class
System.out.println("Max Speed subclass "+maxspeed);
System.out.println("Max Speed"+super.maxspeed);
}
}
// Driver program to Myclass
class MyClass{
public static void main(String args[]){
Car obj = new Car();
obj.display();
}
}



super() is used to invoke immediate parent class constructor.

/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to MyClass*/
class MyClass
{
public static void main(String[] args)
{
Student s = new Student();
}
}


super is used to invoke immediate parent class method

/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that show() is only in Student class
void show()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to MyClass */
class MyClass
{
public static void main(String args[])
{
Student s = new Student();
// calling show() of Student
s.show();
}
}