Java super keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 20 August 2019   |   Print Email
In Java, the super keyword is used to access variables and methods of a super class from a sub class. For example:
public class Super {
protected int number;
protected showNumber() {
System.out.println("number = " + number);
}
}
public class Sub extends Super {
void bar() {
super.number = 10;
super.showNumber();
}
}In the above example, the class Sub accesses the variable number and calls the method showNumber() for its super class Super.
Related keyword: this. See all keywords in Java.
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
protected int number;
protected void showNumber(){
System.out.println("numer : " +number);
}
}
public class SubClassTest extends Super {
void bar(){
super.number =10;
super.showNumber();
}
public static void main(String[]args) {
SubClassTest obj = new SubClassTest();
obj.bar();
}
}