មេរៀនទី១៧: super keyword

super គឺយោងតាមអថេរ ដែលត្រូវបានប្រើ សម្រាប់ parent class object។
ប្រើ super Keyword
1.    super ត្រូវបានប្រើសម្រាប់អថេរ parent class។
2.    super() ត្រូវបានប្រើសម្រាប់ដំឡើង parent class constructor។
1) បញ្ហាមិនប្រើ super keyword
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Output:100
ដំណោះស្រាយពេលប្រើ super keyword
//example of super keyword  
class Vehicle{
int speed=50;
}
class Bike4 extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
Output:50
2) super ប្រើដើម្បី parent class constructor
លោកអ្នកអាចប្រ super keyword ដើម្បីដំលើង parent class constructor ដូចខាងក្រោមនេះ:
class Vehicle{
Vehicle(){System.out.println(“Vehicle is created”);}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println(“Bike is created”);
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
Output:Vehicle is created
Bike is created
super() ត្រូវបានបន្ថែមទៅក្នុង class constructor និមួយៗដោយស្វ័យប្រវត្តិដោយ compiler។
Javaដូចយើងដឹងថា default constructor ត្រូវបានផ្តល់ compiler ដោយស្វ័យប្រវត្តិ វាបន្ថែម super() សម្រាប់ statement ដំបូង។ ប្រសិនបើលោកអ្នក កំពុងបង្កើត constructor របស់អ្នកដោយផ្ទាល់ លោកអ្នកមិនប្រើ () ឬ super() ដូចជា statement ដំបូង ដែល compiler នឹងផ្តល់ super() ។
ឧទាហរណ៍នៃ super keyword កាលណា super() ត្រូវបានផ្តល់ដោយ compiler ។
class Vehicle{
Vehicle(){System.out.println(“Vehicle is created”);}
}
class Bike6 extends Vehicle{
int speed;
Bike6(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike6 b=new Bike6(10);
}
}
Output:Vehicle is created
10
3) super អាចប្រើជាមួយ parent class method។
super keyword អាចប្រើ parent class method វានឹងប្រើក្នុងករណីផ្ទុក subclass ដូចជា method ដូច parent class បង្ហាញឧទាហរណ៍ខាងក្រោម:
class Person{
void message(){System.out.println(“welcome”);}
}
class Student16 extends Person{
void message(){System.out.println(“welcome to java”);}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:welcome to java
welcome
ក្នុងករណីនេះ មិនមាន method ក្នុង subclass ដូចជា parent, វាមិនត្រូវការប្រើ super។ ក្នុងឧទាហរណ៍នេះ បានអោយ message() method ពី Student class ប៉ុន្តែ Student class មិនមាន message() method ដូច្នេះលោកអ្នក អាចហៅផ្ទាល់ message() method។
កម្មវិធីករណីមិនប្រើ super
class Person{
void message(){System.out.println(“welcome”);}
}
class Student17 extends Person{
void display(){
message();//will invoke parent class message() method
}
public static void main(String args[]){
Student17 s=new Student17();
s.display();
}
}
Output:welcome