Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

OOPs Concept (Over-riding)

 
Nishant Hadole
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output of code below is "Sachin" and not "Nishant", just need explanation for the same...

class BaseClass{

protected String name="Sachin";

public void printName(){
System.out.println(name);
}
}

public class MyClass extends BaseClass{
private String name="Nishant";

public static void main(String[] args){

MyClass myClassObj = new MyClass();
myClassObj.printName();

}
}
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hint: Try overriding the method.

Also please use code tags when you display code in a POST
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that member variables cannot be overridden. Only methods can be overridden.
 
Rakesh Chaudhary
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope this helps...

class BaseClass
{

protected String name="Sachin";

public void printName()
{
System.out.println(name);
}
}

public class MyClass extends BaseClass
{
private String name="Nishant";

public void printName()
{
System.out.println(name);
}

public static void main(String[] args){

BaseClass myClassObj = new MyClass();
myClassObj.printName();

}

}

Byee....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic