what is a superclass in java code example
Example 1: super keyword in java
Variables and methods of super class can
be overridden in subclass.
In case of overriding , a subclass
object call its own variables and methods.
Subclass cannot access the variables and
methods of superclass because the overridden
variables or methods hides the
methods and variables of super class.
But still java provides a way to access
super class members even if
its members are overridden. Super is
used to access superclass variables, methods, constructors.
Super can be used in two forms :
1) First form is for calling super class constructor.
2) Second one is to call super class variables,methods.
Super if present must be the first statement.
Example 2: how to create a subclass in java
class Super {
Number aNumber;
}
class Sub extends Super {
Float aNumber;
}
Example 3: how to make one java class inherit from another
public class Bicycle {
public int cadence;
public int gear;
public int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
Example 4: super keyword in java
class Manager
{
int salary = 50000;
}
class Employee extends Manager
{
int salary = 20000;
void display(int salary)
{
System.out.println(super.salary);
}
public static void main(String[] args)
{
Employee obj = new Employee();
obj.display(30000);
}
}