Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance: Calling a subclass method in a superclass

I'm very new to java and would like to know whether calling a subclass method in a superclass is possible. And if doing inheritance, where is the proper place to set public static void main.

Superclass

public class User {
    private String name;
    private int age;

    public User() {
        //Constructor
    }

    //Overloaded constructor
    public User(String name, int age) {
        this.name = name; 
        this.age = age;
    }

    public String getName() {
        return this.name;
    }
    public static void main(String []args) {
        User user1 = new Admin("Bill", 18, 2); 

        System.out.println("Hello "+user1.getName()); 
        user1.getLevel();
    }

}

Subclass

public class Admin extends User {

    private int permissionLevel;

    public Admin() {
    //Constructor 
    }

    //Overloading constructor
    public Admin(String name, int age, int permissionLevel) {
        super(name, age); 
        this.permissionLevel = permissionLevel;
    }

    public void getLevel() {
        System.out.println("Hello "+permissionLevel);

    }

}
like image 309
Chansters Avatar asked Jun 17 '17 12:06

Chansters


2 Answers

I'm very new to java and would like to know whether calling a subclass method in a superclass is possible.

A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.

where is the proper place to set public static void main.

I wouldn't recommend putting the main method in the Admin class nor the User class for many factors. Rather create a separate class to encapsulate the main method.

Example:

public class Main{
   public static void main(String []args) {
        User user1 = new Admin("Bill", 18, 2); 

        System.out.println("Hello "+user1.getName()); 
        user1.getLevel();
    }
}
like image 185
Ousmane D. Avatar answered Sep 20 '22 13:09

Ousmane D.


Short answer: No.

Medium answer: Yes, but you have to declare the method in the superclass. Then override it in the subclass. The method body from the subclass will be in invoked when the superclass calls it. In your example, you could just put an empty getLevel method on User.

You could also consider declaring User as an abstract class and declaring the getLevel method as abstract on the User class. That means you don't put any method body in getLevel of the User class but every subclass would have to include one. Meanwhile, User can reference getLevel and use the implementation of its subclass. I think that's the behavior you're going for here.

like image 38
mymarkers Avatar answered Sep 21 '22 13:09

mymarkers