26 - Super Keyword in Java
26 - Super Keyword in Java
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
Note
In the above example Vehicle and Bike both class have a common
property speed. Instance variable of current class is refered by
instance bydefault, but I have to refer parent class instance variable
that is why we use super keyword to distinguish between parent
class instance variable and current class instance variable.
Solution by super keyword
//example of super keyword
class Vehicle{
int speed=50;
}
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 is used to invoke parent class
constructor.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
}
}
Output: Vehicle is created Bike is created
• Note: super() is added in each class
constructor automatically by compiler.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
• 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
Java Package
Java Package
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two
form, built-in package and user-defined
package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of
creating and using user-defined packages.
Advantage of Java Package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
Output:Welcome to package
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
• Output:Hello