function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ken KoellnerKen Koellner 

Method override, do I have to cast to get more specific method

If I have a subclass that overrides a method in a superclass, do I have to cast a reference to get the more specific reference.  The superclass is virtual, not abstract as it has to implement some logic.

 

Example class definition--

 

public virtual class MySuperClass {
 
  public virtual boolean myMethod () {
     // code goes here
     return result;
  }

}

public class MySubClass {
 
  public override boolean myMethod () {
     // code goes here
     return result;
  }

}

 Example call --

 

MySuperClass myObj = new MySubClass();

// Does this call MySuperClass.validate() or MySubClass.validte() ?
Boolean result = myObj.myMethod();


// Do I have to do this to call MySubClass.validate() ?
Boolean result = (myObj(MySubClass)).myMethod();

 

Best Answer chosen by Admin (Salesforce Developers) 
Anup JadhavAnup Jadhav

No, you don't need to cast. So essentially:

public class MySuperClass {
 
  public virtual String myMethod () {
     // code goes here
     return 'parent method';
  }

}

public class MySubClass extends MySuperClass {
 
  public override String myMethod () {
     // code goes here
     return 'child method';
  }

}

MySuperClass myObj = new MySubClass();

system.debug(' myObj.myMethod() = '+ myObj.myMethod());
// will output myObj.myMethod() = child method

 

Hope this helps!

 

- Anup

All Answers

Anup JadhavAnup Jadhav

No, you don't need to cast. So essentially:

public class MySuperClass {
 
  public virtual String myMethod () {
     // code goes here
     return 'parent method';
  }

}

public class MySubClass extends MySuperClass {
 
  public override String myMethod () {
     // code goes here
     return 'child method';
  }

}

MySuperClass myObj = new MySubClass();

system.debug(' myObj.myMethod() = '+ myObj.myMethod());
// will output myObj.myMethod() = child method

 

Hope this helps!

 

- Anup

This was selected as the best answer
Ken KoellnerKen Koellner

Indeed you are correct. 

 

I forgot that you can define classes in anonymous apex.  I just ran this as an example to proove it --

 

public class MySuperClass {
 
  public virtual String myMethod () {
     return 'parent method';
  }

}

public class MySubClass extends MySuperClass {
 
  public override String myMethod () {
     return 'child method';
  }

}

MySuperClass myObj = new MySubClass();

system.debug(' xyzzy  '+ myObj.myMethod());

 

Anup JadhavAnup Jadhav

Thanks! Yeah :) That's how I normally prove or disprove my suspicions when I am in doubt about the language feature. I use the Developer Console. It is my new best friend.

 

- Anup