C
C
Core Java
Search…
22) Super Keyword
1
package com.gns.sort;
2
3
/* Base class vehicle */
4
class Vehicle {
5
int maxSpeed = 120;
6
}
7
8
/* sub class Car extending vehicle */
9
class Car extends Vehicle {
10
int maxSpeed = 180;
11
12
void display() {
13
/* print maxSpeed of base class (vehicle) */
14
System.out.println("Maximum Speed: " + super.maxSpeed);
15
}
16
}
17
18
/* Driver program to test */
19
public class Test {
20
public static void main(String[] args) {
21
Car small = new Car();
22
small.display();
23
}
24
}
Copied!
1
Output:
2
Maximum Speed: 120
3
In the above example, both base class and subclass have a member maxSpeed. We could access maxSpeed of base class in sublcass using super keyword.
Copied!
1
package com.gns.sort;
2
3
/* Base class Person */
4
class Person {
5
void message() {
6
System.out.println("This is person class");
7
}
8
}
9
10
/* Subclass Student */
11
class Student extends Person {
12
void message() {
13
System.out.println("This is student class");
14
}
15
16
// Note that display() is only in Student class
17
void display() {
18
// will invoke or call current class message() method
19
message();
20
21
// will invoke or call parent class message() method
22
super.message();
23
}
24
}
25
26
/* Driver program to test */
27
public class Test {
28
public static void main(String args[]) {
29
Student s = new Student();
30
31
// calling display() of Student
32
s.display();
33
}
34
}
Copied!
1
Output:
2
This is student class
3
This is person class
Copied!
1
package com.gns.sort;
2
3
/* superclass Person */
4
class Person {
5
Person() {
6
System.out.println("Person class Constructor");
7
}
8
}
9
10
/* subclass Student extending the Person class */
11
class Student extends Person {
12
Student() {
13
// invoke or call parent class constructor
14
super();
15
16
System.out.println("Student class Constructor");
17
}
18
}
19
20
/* Driver program to test */
21
class Test {
22
public static void main(String[] args) {
23
Student s = new Student();
24
}
25
}
Copied!
1
Output:
2
Person class Constructor
3
Student class Constructor
Copied!

Example 1:

Example 2:

Example 3:

Problems :

Last modified 2yr ago