File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about subclasses and superclasses.

 
matthew meltzer
Greenhorn
Posts: 24
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"it can create an object of B in A" is incorrect wording.
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 231
Java Notepad Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
a.run();
}
}

you may compile the above code and learn a lot of things by changing refrences ...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic