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
MikeGinouMikeGinou 

Cannot call overriden protected virtual methods from superclass?

Is this an Apex bug, documented limitation, or am I just crazy to think that the following should be possible?

 

Here is a simple example demonstrating an example of attempting to call an overridden implementation of a protected method from a superclass. I've set the example as three separate class files:

 

Parent Class:

 

public virtual class TestParent {
	  private string data = 'Parent Data';
	
	  protected virtual string getData() {
	    return this.data;
	  }
	
	  public string getText()
	  { // This is where the Overwritten child method gets called!
	    return 'Data : ' + this.getData();
	  }
}

Child Class:

 

public class TestChild extends TestParent {
	private string myData = 'Child Data';

	protected override string getData() {
		return super.getData() + ' and ' + myData;
	}
}

 Test Class:

 

@isTest
private class inheritancetest {
	static testmethod void testUseChild()
	{
		try {
			TestChild c = new TestChild();
			c.getText();
		} catch (Exception e) {
			System.Assert( false, 'Exception! ' + e.getMessage() );
		}
	}
	
	static testmethod void testUseParent()
	{
		try {
			TestParent p = new TestChild();
			p.getText();
		} catch (Exception e) {
			System.Assert( false, 'Exception! ' + e.getMessage() );
		}
	}
}

 

I was expecting the test methods to pass without any issues, instead they fail because "[TestChild].getData() is not accessible", (a line number indicating Test.Parent.getText()'s code statement is provided).

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

According to the Apex Developer's Guide:

 

 

---

 

 

protected
This means that the method or variable is visible to any inner classes in the defining Apex class.

 

protected

 

This means that the method or variable is visible to any inner classes in the defining Apex class.

 

---

 

Thus it sounds like what you are experiencing is correct behaviour.

 

All Answers

bob_buzzardbob_buzzard

According to the Apex Developer's Guide:

 

 

---

 

 

protected
This means that the method or variable is visible to any inner classes in the defining Apex class.

 

protected

 

This means that the method or variable is visible to any inner classes in the defining Apex class.

 

---

 

Thus it sounds like what you are experiencing is correct behaviour.

 

This was selected as the best answer
MikeGinouMikeGinou

I did read that at one point, however, protected methods in the super class are callable by sub classes (I don't have examples of that in the code chunk posted), so the Apex documentation is being a little coy and not sharing the whole truth.