Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Simplest Problem but i am unable to understand it, WHY???

  1. #1
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Simplest Problem but i am unable to understand it, WHY???

    Well, it is the simplest OOP concept, i also know that it happens like this, but i am still confused, since i read it the very first time. I like to post this here. May be someone could provide me such a logic that could satisfy me.

    PROBLEM:

    We know that a super class's object can refer to a sub class object. i.e.

    // Class A
    class A{
            private int a;
            private int b;
            A(){
                    a=0;
                    b=0;
                }
                A(int a, int b){
                        this.a=a;
                        this.b=b;
                }
                public show(){
                    System.out.println(a+","+b);
                }
     
        }

    // Class B
    class B extends A{
            private int c;
            B(){
                    super();
                    c=0;
                }
                B(int a, int b, int c){
                        super(a,b);
                        this.c=c;
                }
                public show(){
                    System.out.println(c);
                }
                public add(){
                    System.out.println("Test");
                }
        }

    // Main class
    class Test{
        public static void main(String args[]){
                 A a=new A(1,2);
                 B b=new B(3,4,5);
                 a.show(); // 1 2
                 b.show(); // 5
                 b.add(); // Hello
                 a = b; // Super class reference to Sub class.
                 a.show(); // 3,4
                 b.show(); // 5
                 a.add(); // Error. 
        }
    }

    I am actually confused at this statement where it gives error.
    a.add();
    I am confused here. Why it is so? I can not understand, as "a" has been referenced to "b" and we all know the concept of referece. So, why "a" can not call add() here? I know, you will say it's not implemented in A, i know, but why?

    DISCUSS PLEASE...
    Last edited by Mr.777; October 25th, 2011 at 06:50 AM.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    I just counted 20 compiler errors in that code. Are you sure everything works how you think it does? Fix them and create an SSCCE that demonstrates what you're talking about, and we'll go from there.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    My code was messed together. I just wrote it in notepad++, i don't want you to compile or let me run this code. I know enough about OOP. I just want you to discuss the concept, i am confused in.
    In the main() function, there is a line a.add(); which is actually an error.
    Coz class A has never implemented add(), but i want to know that as "a" is now referenced to "b", why so????

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Like I said. We can help you when you provide an SSCCE. Talking in theory is fine, but it is a thousand times easier when we have some common working code to which we can refer. Plus that code contains some things that make me suspect you're working off incorrect assumptions, so creating an SSCCE will help clear them up. It shouldn't take more than a minute (it will take less time than it took to write these posts).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Did you see my code Kevin?
    I have already fixed it before posting second time.
    Kindly review the code and look at the main() too.

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Okay. I still had to fix your method declarations, but good enough.

    The reason it's saying that the add() method is not defined in type A is because, well, it isn't. And your 'a' variable is of type A, so the compiler has no idea what subclass might be stored in it. For example, you could have an instance of some class C that extends A and does not have the add() method stored in the 'a' variable.

    Here's an SSCCE that demonstrates what I'm talking about a little more clearly:

     
    public class Test
    {
     
    	public static void main(String args[]){
    		Animal animal = new Animal();
    		Cat cat = new Cat();
    		animal.eat();
    		cat.meow();
     
    		animal = cat;
    		animal.meow(); //error
     
    		animal = new Dog();
    		animal.meow(); //error, for more obvious reasons
     
    	}
    }
     
    class Animal{
    	public void eat(){
    		System.out.println("Animal eating.");
    	}
    }
     
    class Cat extends Animal{
    	public void meow(){
    		System.out.println("Meow");
    	}
    }
     
    class Dog extends Animal{
    	public void bark(){
    		System.out.println("Bark");
    	}
    }
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Kevin, what you tried to do is, you just referenved superclass to the subclass say dog, but you tried to call the function from cat.
    I am not talking about this.

    Let's say, there is a function called "color()" in class Dog but not in class Animal.
    And i do this,
    Animal animal=new Dog();
    animal.color(); // This will create an error, right???
    So, why will animal.color() will give error????
    as you can see that animal is now referenced as dog. That is the actual confusion. I know, that it will generate error. But i want to know, why? What is the true reason? According to the reference concept, say
    String a="Hi";
    String b="Bye";
    a=b;
    System.out.println(a);
    System.out.println(b);
    Both print statements will generate the same result. It's reference, actually the object is given the address of the right side object.

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Quote Originally Posted by Mr.777 View Post
    Kevin, what you tried to do is, you just referenved superclass to the subclass say dog, but you tried to call the function from cat.
    I am not talking about this.
    Yes, you are. That's the point. The compiler has no way to know what you're storing in the superclass variable. It has no way to know what methods the subclasses are going to have. So even though you might know that a Cat can meow, unless you explicitly store (or cast) the reference as a Cat, you won't be able to use any Cat methods. This is because the compiler has no way to know it's a Cat or a Dog or a Fish or whatever. The same exact thing applies to your code.

    Quote Originally Posted by Mr.777 View Post
    Let's say, there is a function called "color()" in class Dog but not in class Animal.
    And i do this,
    Animal animal=new Dog();
    animal.color(); // This will create an error, right???
    So, why will animal.color() will give error????
    Because you're storing it as an Animal, so the compiler has no way to know what's in there. What if you had a List of Animals, each being a different subclass? The compiler can't know what a reference is storing, only what the reference claims to be. So since all you're claiming to be is an Animal, you can only use methods available to the Animal class. That's exactly what my example shows. Please go over it again carefully.

    Quote Originally Posted by Mr.777 View Post
    as you can see that animal is now referenced as dog. That is the actual confusion. I know, that it will generate error. But i want to know, why? What is the true reason?
    No, the reference is still an Animal. The instance may be a Dog, but the compiler can't know that.

    Quote Originally Posted by Mr.777 View Post
    According to the reference concept, say
    String a="Hi";
    String b="Bye";
    a=b;
    System.out.println(a);
    System.out.println(b);
    Both print statements will generate the same result. It's reference, actually the object is given the address of the right side object.
    This doesn't have much to do with your original question. In this case, both a and b are Strings. But what would happen if you did something like this?

    public class Test
    {
     
    	public static void main(String args[]){
    		String string1 = "test1";
    		Object string2 = string1;
     
    		System.out.println(string2.toUpperCase());
    	}
    }

    You have a fundamental misunderstanding of how inheritance works with regards to references and instances. I suggest you read up on the basic tutorials and try more examples before you claim that my code is not what you're talking about.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Mr.777 (October 26th, 2011)

  10. #9

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Mr. 777,

    You have a logical error in your post that
    We know that a super class's object can refer to a sub class object
    'a' is not an object, it is a reference to an object of type A.

    You have classes A and B where B is a subclass of A.

    In your code, you write:
    A a=new A(1,2);
    B b=new B(3,4,5);
    Then you go on to write:
     a = b; // Super class reference to Sub class.
    a.show(); // 3,4
    b.show(); // 5
    a.add(); // Error.
    a = b; is valid because b is of type B which is a sublclass of A, so it is a type of A

    but your statement a.add(); is a huge mistake because there is no add() method in class A. Class B is the only class with an add() method. What you have done with a = b; is you have hidden all the things that makes a B a B and you have forced it to conform to A's definition. You can cast 'a' as a B and achieve its add functionality that way, but as long as you are not explicitly typecasting your 'a' variable, you are stuck with the public methods of A, and this only works because B is a type of A.

    Kevin's example, while it may not be as clear as you need it to be, is spot on. He uses class Animal (Class A) and has a subclass Cat (Class B).
    He creates the references and an instance of Cat and assigns it to Animal. He then tries to make the Animal meow.... but not all animals meow. Even though you may be able to tell the difference between a Cat and an Animal, the Java compiler doesn't. That's why I talked about casting. Casting tells the compiler explicitly that the Animal it is looking at is a Cat.

    Consider that you have another class C that extends A and it has a method subtract. You apply the same logic as with B.

    a = c;
    a.subtract();

    Do you expect this to work? It won't because the subtract() method is not a part of class A. It's all about being type-safe. Java is a strongly-typed language, so you can't get away with things like calling another classes methods.
    Type safety - Wikipedia, the free encyclopedia
    Kenneth Walter
    Software Developer
    http://kennywalter.com

  11. The Following 3 Users Say Thank You to kenster421 For This Useful Post:

    KevinWorkman (October 25th, 2011), Mr.777 (October 26th, 2011), william (October 26th, 2011)

  12. #10
    Junior Member
    Join Date
    Oct 2011
    Location
    Lucknow,India
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    The problem you are facing is called Object Slicing in CPP. It happens when any base class object/pointer is used to access the object of the derived class. The extra features i.e. the members are unknown to the base class object.The virtual base pointer is unknown of it. I m not very clear what exactly is the technicality in JAVA for this. But if u want to the idea, its object slicing...

    Very simply if CAR is a base class and Mercedes is a subclass of it. No doubt every feature of CAR is in MERCEDES.But every feature of Mercedes is not in CAR, like the ABS,EPS..So it can't be referred by a base class CAR!!

  13. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    I don't know much about c++, but I would like to correct one thing from the Java perspective:

    Quote Originally Posted by ashutoshtiwari View Post
    Very simply if CAR is a base class and Mercedes is a subclass of it. No doubt every feature of CAR is in MERCEDES.But every feature of Mercedes is not in CAR, like the ABS,EPS..So it can't be referred by a base class CAR!!
    A Mercedes can be referenced as a Car, like so:

    Car car = new Mercedes();

    However, without casting, the car variable cannot access the methods in Mercedes (which I think is what you meant).

    That might just be a case of me being pedantic with your terminology, but I didn't want the OP to become more confused.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  14. #12
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Simplest Problem but i am unable to understand it, WHY???

    Oh yes Kevin, thanks alot. I was confused in instance and reference.
    I got your point and all others who helped me.
    Thanks alot.

Similar Threads

  1. Help me to understand this
    By Madhushan in forum Java Theory & Questions
    Replies: 2
    Last Post: September 10th, 2011, 08:47 AM
  2. I can't understand the error.
    By Shivam24 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: July 21st, 2011, 01:56 PM
  3. I don't understand what I'm supposed to do
    By dmcettrick in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 11th, 2011, 09:34 AM
  4. I dont understand why this happens....
    By ashenwolf in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 10th, 2011, 09:31 PM
  5. Can't understand why Interfaces are there
    By vortexnl in forum Object Oriented Programming
    Replies: 9
    Last Post: February 14th, 2011, 01:06 PM