0

When I change this code into Member m1 = new Member (); It works perfectly. Why it does not work for Super class reference? Please can someone explain?

public class Family {

String Surname = "Richard";
String Address = "No:10, High Street,Colombo";

}

public class Member extends Family{

String Name;
int age;

public void Details() {
    System.out.println("full Name ="+ Name +" "+ Surname);
    System.out.println("Age =" +age);
    System.out.println("Address =" + Address);
}

public static void main(String[] args) {
    Member m1 =  new Family ();

    m1.Name="Anne";
    m1.age=24;

    m1.Details();

}
1
  • 1
    Possible duplicate of this Commented Feb 10, 2013 at 7:04

1 Answer 1

7

You don't have a super class reference. You are having a subclass reference holding a reference to a super class object, that is simply illegal.

Secondly, you need to defined the method you have in subclass also in super class, if you want to see polymorphism into effect. You can only invoke that method on super class reference, that is also defined in super class.

So, you basically need this: -

Family m1 =  new Member();

and then define the details() method(Yes, method name should start with lowercase alphabets), in your Family class.

And now, you will get another compiler error, when you try to access the fields of Member. For that, it's better to use a 2-arg constructor in Member class, and from that constructor, invoke the 2-arg super constructor (you need to do this explicitly), or 0-arg super constructor (this is implicit)

public Member(String name, int age) {
    this.name = name;
    this.age = age;
}

And use this constructor to create the object. It will implicitly call the 0-arg super constructor to initialize it's fields with their default value. If you want to give them a value, you can use a 4-arg constructor in Member class, passing the 2-parameters for super class fields, and then invoke the super class 2-arg constructor from there.

I think, you should better start with a good tutorial, starting with learning Inheritance in general, the access specifiers, then move ahead with polymorphism.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.