Question

Please see the code below for an example of my question:

    class Person  
    {  
        private  String name;  
        public  
            String toString()  
            {  
                return this.name;  
            }  
    }

    class Student extends Person  
    {  
       private  int no_of_courses;  
       public  
           @Override String toString()  {  return "Student " + super.toString();  }
    }  
    class SuperDemo  
    {  
        public static void main(String[] args)  
        {  
            Person p = new Student("ABC,"XYZ");  
            System.out.println(p.toString());  
        }  
    }

Can we Override a public method of a super class in the derived class? The Person class has the Constructor:

Person(String name)

The Student class has the constructor:

Student(String name) { super(name); }

Was it helpful?

Solution

Yes. You already do this naturally when overriding toString() from Object.

You cannot override:

  • Anything marked final
  • Anything static
  • Anything private

You also cannot reduce the visibility of an overridden method; that is, you can't override a public method into a protected one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top