wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question about subclasses and superclasses. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question about subclasses and superclasses." Watch "question about subclasses and superclasses." New topic

question about subclasses and superclasses.

matthew meltzer

Joined: Sep 08, 2012
Posts: 24

Here is the code i'm working with.

I have to explain the error in the above code beyond just what the compiler tells me. Since A is a subclass of B it can create an object of B in A since the subclass inherits methods, variables, etc from the superclass. However since A is the superclass and not a subclass of B it cannot be created into an object of B.

Am I on the right track or am I wrong? Any help would be appreciated. Thanks!

-Matthew Meltzer
Alexei Kaigorodov

Joined: Feb 24, 2008
Posts: 17
"it can create an object of B in A" is incorrect wording.
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

here A is the subclass and B is the superclass. now a superclass can refer to its subclass object. i.e. you can do B b = new A(); but you CANNOT do A a = new B(); to understand this take example of Animal superclass and Dog subclass.

a Dog IS-A Animal. it has inherited all the attributes and behaviour from animal. but, but it defines its own specialized behaviors ( bark) and attributes which are inherent to only Dog. in other words Dog is a specialized type of Animal. so in programming terms we can say that a Dog object can be Converted to Animal type. in other words can be assigned to animal reference. but vice-versa is NOT true. An Animal is NOT a Dog. An animal CANNOT bark.

P.S. when is said CAN BE CONVERTED, keep in mind there is no actual conversion of Dog object to animal. Dog object remains Dog object. it just can be referred to by Animal reference.
shivam singhal
Ranch Hand

Joined: Jul 15, 2012
Posts: 231

if am correctly undersatnd your query then ...
object can reside in parent's reference and vice versa is not true..
that is

public class A{
void run(){
System.out.println("its working by A");
class B extends A{
void run1(){
System.out.println("its working by B");
class TestDrive{
public static void main(String args){
A a = new B();

you may compile the above code and learn a lot of things by changing refrences ...
I agree. Here's the link: http://aspose.com/file-tools
subject: question about subclasses and superclasses.
It's not a secret anymore!