Classes/Objects  «Prev 


Casting Parent reference object to Child

In the code below, a parent reference variable has been cast to Child Object so that the parent reference variable can access the method
void speak(String s)

11 in the subclass Child.

class Parent {
	protected void speak() {
		System.out.println("Parent speaks");
	}
}

class Child extends Parent {
	public void speak() {
		System.out.println("Child spekas");
	}

	void speak(String s) {
		System.out.println(s);
	}
}

public class Driver {

	public static void main(String[] args) {
		Parent s1 = new Child();	// line 1
		//Parent s1 = new Parent();	// line 2
		((Child) s1).speak("Parent has been cast "); // line 3 

	}
}
/* Program output 
Parent has been cast 
*/