wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes OOPs Concept (Over-riding) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "OOPs Concept (Over-riding)" Watch "OOPs Concept (Over-riding)" New topic
Author

OOPs Concept (Over-riding)

Nishant Hadole
Greenhorn

Joined: Apr 24, 2008
Posts: 4
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

Joined: Feb 24, 2006
Posts: 6661
    
    5

Hint: Try overriding the method.

Also please use code tags when you display code in a POST


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Note that member variables cannot be overridden. Only methods can be overridden.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rakesh Chaudhary
Ranch Hand

Joined: Feb 19, 2008
Posts: 120
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....


Acquire the unexpected.......
Preparing for SCJP 6
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: OOPs Concept (Over-riding)
 
Similar Threads
Java Generics Problem
multiple casting
Constructor & Polymorphism
Superclass has subclass reference
an parent object's lock