What is wrong with line 1?

public class G
{
private int x;
public G() { x=3;}
public void setX(int val){
x=val;
}
public String toString(){
return ""+x;
}
}

public class H extends G
{
private int y;
public H() { y=4;}
public void setY(int val){
y=val;
}
public String toString() {
return ""+y+super.toString();
}
}

//test code in the main method
G bad = new H();
bad.setY(9); //line 1

Respuesta :

Answer:

The set is a object of the class 'H' and the setY method is a member of G class which is not called by the object of H class.

Explanation:

  • If a user calls the G function which is not a private by the help of H class objects then it can be called. It is because all the public and protected methods of A class can be accessed by the B class if B extends the A-class.
  • If any class is extended by the other class then the derived class holds the property of the base class and the public and protected method can be accessed by the help of a derived class object.
  • The derived class object can be created by the help of base class like written in the "line 1".
  • But the base class can not call the member of the derived class.