Override class parameter type in JavaWhen to implement an interface and when to extend a superclass?Is Java “pass-by-reference” or “pass-by-value”?Java inner class and static nested classHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Why is it important to override GetHashCode when Equals method is overridden?Set a default parameter value for a JavaScript functionDoes Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with Java

How should I deal with a potential date who wouldn’t take no for an answer?

Why command hierarchy, if the chain of command is standing next to each other?

How is являться different from есть and быть

Are there any other rule mechanics that could grant Thieves' Cant?

Iteratively and adaptively increasing the network size during training

Do beef farmed pastures net remove carbon emissions?

A torrent of foreign terms

Super Duper Vdd stiffening required on 555 timer, what is the best way?

Can renaming a method preserve encapsulation?

If "more guns less crime", how do gun advocates explain that the EU has less crime than the US?

What should I call bands of armed men in the Middle Ages?

How far did Gandalf and the Balrog drop from the bridge in Moria?

The cat exchanges places with a drawing of the cat

Is it okay for a ticket seller to grab a tip in the USA?

Are differences between uniformly distributed numbers uniformly distributed?

Split phone numbers into groups based on first digit

Translation of "I don't have anything to smile about"

Is there a way to count the number of lines of text in a file including non-delimited ones?

Why is there a large performance impact when looping over an array over 240 elements?

Is there any way to stop a user from creating executables and running them?

Can I enter the USA with an E-2 visa and a one way flight ticket?

If you know the location of an invisible creature, can you attack it?

How much can I judge a company based on a phone screening?

Does fossil fuels use since 1990 account for half of all the fossil fuels used in history?



Override class parameter type in Java


When to implement an interface and when to extend a superclass?Is Java “pass-by-reference” or “pass-by-value”?Java inner class and static nested classHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Why is it important to override GetHashCode when Equals method is overridden?Set a default parameter value for a JavaScript functionDoes Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with Java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Is it possible to override a class parameter in Java? I'm pretty sure it is not possible but...



public class Dad 
protected Building home;

public Dad()


public Building getHome()
return this.home;



public class Son extends Dad
protected Shack home;

public Son ()
super();
this.home = new Shack();



public Shack extends Building
(...)



Apparently, there is no problem in adding two paraters with the same name but i'm not sure the two parameters are "link" together..



When I'm calling the getHome() function from a Son object, it returns a null object. Which make sense because the Dad object has no initialised Building object. Even if Son has a initialise Shack object that extends Building class. (I don't know if I'm clear enough...)



A simple solution would be to simply initialise home with a Shack object and cast home in Shack whenever it is necessary. But I'd like to know if there is another way to do this.










share|improve this question
























  • super.home = .... But it would be better to pass it as a constructor parameter to Dad.

    – Andy Turner
    Mar 27 at 10:06












  • "i'm not sure the two parameters are "link" together.." They're not.

    – Andy Turner
    Mar 27 at 10:07


















0















Is it possible to override a class parameter in Java? I'm pretty sure it is not possible but...



public class Dad 
protected Building home;

public Dad()


public Building getHome()
return this.home;



public class Son extends Dad
protected Shack home;

public Son ()
super();
this.home = new Shack();



public Shack extends Building
(...)



Apparently, there is no problem in adding two paraters with the same name but i'm not sure the two parameters are "link" together..



When I'm calling the getHome() function from a Son object, it returns a null object. Which make sense because the Dad object has no initialised Building object. Even if Son has a initialise Shack object that extends Building class. (I don't know if I'm clear enough...)



A simple solution would be to simply initialise home with a Shack object and cast home in Shack whenever it is necessary. But I'd like to know if there is another way to do this.










share|improve this question
























  • super.home = .... But it would be better to pass it as a constructor parameter to Dad.

    – Andy Turner
    Mar 27 at 10:06












  • "i'm not sure the two parameters are "link" together.." They're not.

    – Andy Turner
    Mar 27 at 10:07














0












0








0








Is it possible to override a class parameter in Java? I'm pretty sure it is not possible but...



public class Dad 
protected Building home;

public Dad()


public Building getHome()
return this.home;



public class Son extends Dad
protected Shack home;

public Son ()
super();
this.home = new Shack();



public Shack extends Building
(...)



Apparently, there is no problem in adding two paraters with the same name but i'm not sure the two parameters are "link" together..



When I'm calling the getHome() function from a Son object, it returns a null object. Which make sense because the Dad object has no initialised Building object. Even if Son has a initialise Shack object that extends Building class. (I don't know if I'm clear enough...)



A simple solution would be to simply initialise home with a Shack object and cast home in Shack whenever it is necessary. But I'd like to know if there is another way to do this.










share|improve this question














Is it possible to override a class parameter in Java? I'm pretty sure it is not possible but...



public class Dad 
protected Building home;

public Dad()


public Building getHome()
return this.home;



public class Son extends Dad
protected Shack home;

public Son ()
super();
this.home = new Shack();



public Shack extends Building
(...)



Apparently, there is no problem in adding two paraters with the same name but i'm not sure the two parameters are "link" together..



When I'm calling the getHome() function from a Son object, it returns a null object. Which make sense because the Dad object has no initialised Building object. Even if Son has a initialise Shack object that extends Building class. (I don't know if I'm clear enough...)



A simple solution would be to simply initialise home with a Shack object and cast home in Shack whenever it is necessary. But I'd like to know if there is another way to do this.







java parameters overriding






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 10:01









M.FerruM.Ferru

1933 silver badges19 bronze badges




1933 silver badges19 bronze badges















  • super.home = .... But it would be better to pass it as a constructor parameter to Dad.

    – Andy Turner
    Mar 27 at 10:06












  • "i'm not sure the two parameters are "link" together.." They're not.

    – Andy Turner
    Mar 27 at 10:07


















  • super.home = .... But it would be better to pass it as a constructor parameter to Dad.

    – Andy Turner
    Mar 27 at 10:06












  • "i'm not sure the two parameters are "link" together.." They're not.

    – Andy Turner
    Mar 27 at 10:07

















super.home = .... But it would be better to pass it as a constructor parameter to Dad.

– Andy Turner
Mar 27 at 10:06






super.home = .... But it would be better to pass it as a constructor parameter to Dad.

– Andy Turner
Mar 27 at 10:06














"i'm not sure the two parameters are "link" together.." They're not.

– Andy Turner
Mar 27 at 10:07






"i'm not sure the two parameters are "link" together.." They're not.

– Andy Turner
Mar 27 at 10:07













3 Answers
3






active

oldest

votes


















1














Fields can't be overriden. In your case field from Son just hiding field from Dad:




Within a class, a field that has the same name as a field in the
superclass hides the superclass's field, even if their types are
different. Within the subclass, the field in the superclass cannot be
referenced by its simple name. [...] Generally
speaking, we don't recommend hiding fields as it makes code difficult
to read.




The GetHome function declared into Dad class, so it can see only home instance form Dad which is null. You could access Dad's home as super.home from Son instance.



You could extract superclass or interface.



interface HasHome 
Building getHome();


class Dad implements HasHome
protected Building home;

public Dad()
this.home = new Building();


@Override
public Building getHome()
return this.home;



class Son implements HasHome // Or extends Dad
protected Shack home;

public Son ()
super();
this.home = new Shack();


@Override
public Shack getHome()
return home;




There is another question which way to choose. More over, supertype can be generic, as @Lorelorelore shows.






share|improve this answer


































    1














    You should not re-declare fields with the same names in subclasses. This is because fields are hidden, not overridden.



    The compiler won't complain about this, but there are two variables in this case. Dad.home is not being assigned by the constructor in Son. So new Son().getHome() will return null in this example, and that's because getHome() only knows about Dad.home.



    From where you are, the best is just to remove the home property from Son, and better yet, make it private in Dad and pass its value from the subclass using constructor parameters.






    share|improve this answer
































      1














      Maybe you should refactor those two classes with generics:



      Abstract superclass:



      public abstract class Person<T extends Building> 
      protected T home;

      public T getHome()
      return this.home;




      Dad class:



      public class Dad extends Person<Building> 

      public Dad()
      home = new Building();





      Son class:



      public class Son extends Person<Shack> 

      public Son ()
      home = new Shack();





      You can check if the home field has the correct type (and also not null) with a simple test:



      public class SonAndDadTest 

      @Test
      public void sonTest()
      Son son = new Son();
      Assert.assertNotNull(son.getHome());
      Assert.assertEquals(son.getHome().getClass(), Shack.class);


      @Test
      public void dadTest()
      Dad dad = new Dad();
      Assert.assertNotNull(dad.getHome());
      Assert.assertEquals(dad.getHome().getClass(), Building.class);








      share|improve this answer



























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374455%2foverride-class-parameter-type-in-java%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Fields can't be overriden. In your case field from Son just hiding field from Dad:




        Within a class, a field that has the same name as a field in the
        superclass hides the superclass's field, even if their types are
        different. Within the subclass, the field in the superclass cannot be
        referenced by its simple name. [...] Generally
        speaking, we don't recommend hiding fields as it makes code difficult
        to read.




        The GetHome function declared into Dad class, so it can see only home instance form Dad which is null. You could access Dad's home as super.home from Son instance.



        You could extract superclass or interface.



        interface HasHome 
        Building getHome();


        class Dad implements HasHome
        protected Building home;

        public Dad()
        this.home = new Building();


        @Override
        public Building getHome()
        return this.home;



        class Son implements HasHome // Or extends Dad
        protected Shack home;

        public Son ()
        super();
        this.home = new Shack();


        @Override
        public Shack getHome()
        return home;




        There is another question which way to choose. More over, supertype can be generic, as @Lorelorelore shows.






        share|improve this answer































          1














          Fields can't be overriden. In your case field from Son just hiding field from Dad:




          Within a class, a field that has the same name as a field in the
          superclass hides the superclass's field, even if their types are
          different. Within the subclass, the field in the superclass cannot be
          referenced by its simple name. [...] Generally
          speaking, we don't recommend hiding fields as it makes code difficult
          to read.




          The GetHome function declared into Dad class, so it can see only home instance form Dad which is null. You could access Dad's home as super.home from Son instance.



          You could extract superclass or interface.



          interface HasHome 
          Building getHome();


          class Dad implements HasHome
          protected Building home;

          public Dad()
          this.home = new Building();


          @Override
          public Building getHome()
          return this.home;



          class Son implements HasHome // Or extends Dad
          protected Shack home;

          public Son ()
          super();
          this.home = new Shack();


          @Override
          public Shack getHome()
          return home;




          There is another question which way to choose. More over, supertype can be generic, as @Lorelorelore shows.






          share|improve this answer





























            1












            1








            1







            Fields can't be overriden. In your case field from Son just hiding field from Dad:




            Within a class, a field that has the same name as a field in the
            superclass hides the superclass's field, even if their types are
            different. Within the subclass, the field in the superclass cannot be
            referenced by its simple name. [...] Generally
            speaking, we don't recommend hiding fields as it makes code difficult
            to read.




            The GetHome function declared into Dad class, so it can see only home instance form Dad which is null. You could access Dad's home as super.home from Son instance.



            You could extract superclass or interface.



            interface HasHome 
            Building getHome();


            class Dad implements HasHome
            protected Building home;

            public Dad()
            this.home = new Building();


            @Override
            public Building getHome()
            return this.home;



            class Son implements HasHome // Or extends Dad
            protected Shack home;

            public Son ()
            super();
            this.home = new Shack();


            @Override
            public Shack getHome()
            return home;




            There is another question which way to choose. More over, supertype can be generic, as @Lorelorelore shows.






            share|improve this answer















            Fields can't be overriden. In your case field from Son just hiding field from Dad:




            Within a class, a field that has the same name as a field in the
            superclass hides the superclass's field, even if their types are
            different. Within the subclass, the field in the superclass cannot be
            referenced by its simple name. [...] Generally
            speaking, we don't recommend hiding fields as it makes code difficult
            to read.




            The GetHome function declared into Dad class, so it can see only home instance form Dad which is null. You could access Dad's home as super.home from Son instance.



            You could extract superclass or interface.



            interface HasHome 
            Building getHome();


            class Dad implements HasHome
            protected Building home;

            public Dad()
            this.home = new Building();


            @Override
            public Building getHome()
            return this.home;



            class Son implements HasHome // Or extends Dad
            protected Shack home;

            public Son ()
            super();
            this.home = new Shack();


            @Override
            public Shack getHome()
            return home;




            There is another question which way to choose. More over, supertype can be generic, as @Lorelorelore shows.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 27 at 10:43

























            answered Mar 27 at 10:09









            Mikhail IlinykhMikhail Ilinykh

            6583 silver badges11 bronze badges




            6583 silver badges11 bronze badges


























                1














                You should not re-declare fields with the same names in subclasses. This is because fields are hidden, not overridden.



                The compiler won't complain about this, but there are two variables in this case. Dad.home is not being assigned by the constructor in Son. So new Son().getHome() will return null in this example, and that's because getHome() only knows about Dad.home.



                From where you are, the best is just to remove the home property from Son, and better yet, make it private in Dad and pass its value from the subclass using constructor parameters.






                share|improve this answer





























                  1














                  You should not re-declare fields with the same names in subclasses. This is because fields are hidden, not overridden.



                  The compiler won't complain about this, but there are two variables in this case. Dad.home is not being assigned by the constructor in Son. So new Son().getHome() will return null in this example, and that's because getHome() only knows about Dad.home.



                  From where you are, the best is just to remove the home property from Son, and better yet, make it private in Dad and pass its value from the subclass using constructor parameters.






                  share|improve this answer



























                    1












                    1








                    1







                    You should not re-declare fields with the same names in subclasses. This is because fields are hidden, not overridden.



                    The compiler won't complain about this, but there are two variables in this case. Dad.home is not being assigned by the constructor in Son. So new Son().getHome() will return null in this example, and that's because getHome() only knows about Dad.home.



                    From where you are, the best is just to remove the home property from Son, and better yet, make it private in Dad and pass its value from the subclass using constructor parameters.






                    share|improve this answer













                    You should not re-declare fields with the same names in subclasses. This is because fields are hidden, not overridden.



                    The compiler won't complain about this, but there are two variables in this case. Dad.home is not being assigned by the constructor in Son. So new Son().getHome() will return null in this example, and that's because getHome() only knows about Dad.home.



                    From where you are, the best is just to remove the home property from Son, and better yet, make it private in Dad and pass its value from the subclass using constructor parameters.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 10:13









                    ernest_kernest_k

                    26.9k4 gold badges32 silver badges55 bronze badges




                    26.9k4 gold badges32 silver badges55 bronze badges
























                        1














                        Maybe you should refactor those two classes with generics:



                        Abstract superclass:



                        public abstract class Person<T extends Building> 
                        protected T home;

                        public T getHome()
                        return this.home;




                        Dad class:



                        public class Dad extends Person<Building> 

                        public Dad()
                        home = new Building();





                        Son class:



                        public class Son extends Person<Shack> 

                        public Son ()
                        home = new Shack();





                        You can check if the home field has the correct type (and also not null) with a simple test:



                        public class SonAndDadTest 

                        @Test
                        public void sonTest()
                        Son son = new Son();
                        Assert.assertNotNull(son.getHome());
                        Assert.assertEquals(son.getHome().getClass(), Shack.class);


                        @Test
                        public void dadTest()
                        Dad dad = new Dad();
                        Assert.assertNotNull(dad.getHome());
                        Assert.assertEquals(dad.getHome().getClass(), Building.class);








                        share|improve this answer





























                          1














                          Maybe you should refactor those two classes with generics:



                          Abstract superclass:



                          public abstract class Person<T extends Building> 
                          protected T home;

                          public T getHome()
                          return this.home;




                          Dad class:



                          public class Dad extends Person<Building> 

                          public Dad()
                          home = new Building();





                          Son class:



                          public class Son extends Person<Shack> 

                          public Son ()
                          home = new Shack();





                          You can check if the home field has the correct type (and also not null) with a simple test:



                          public class SonAndDadTest 

                          @Test
                          public void sonTest()
                          Son son = new Son();
                          Assert.assertNotNull(son.getHome());
                          Assert.assertEquals(son.getHome().getClass(), Shack.class);


                          @Test
                          public void dadTest()
                          Dad dad = new Dad();
                          Assert.assertNotNull(dad.getHome());
                          Assert.assertEquals(dad.getHome().getClass(), Building.class);








                          share|improve this answer



























                            1












                            1








                            1







                            Maybe you should refactor those two classes with generics:



                            Abstract superclass:



                            public abstract class Person<T extends Building> 
                            protected T home;

                            public T getHome()
                            return this.home;




                            Dad class:



                            public class Dad extends Person<Building> 

                            public Dad()
                            home = new Building();





                            Son class:



                            public class Son extends Person<Shack> 

                            public Son ()
                            home = new Shack();





                            You can check if the home field has the correct type (and also not null) with a simple test:



                            public class SonAndDadTest 

                            @Test
                            public void sonTest()
                            Son son = new Son();
                            Assert.assertNotNull(son.getHome());
                            Assert.assertEquals(son.getHome().getClass(), Shack.class);


                            @Test
                            public void dadTest()
                            Dad dad = new Dad();
                            Assert.assertNotNull(dad.getHome());
                            Assert.assertEquals(dad.getHome().getClass(), Building.class);








                            share|improve this answer













                            Maybe you should refactor those two classes with generics:



                            Abstract superclass:



                            public abstract class Person<T extends Building> 
                            protected T home;

                            public T getHome()
                            return this.home;




                            Dad class:



                            public class Dad extends Person<Building> 

                            public Dad()
                            home = new Building();





                            Son class:



                            public class Son extends Person<Shack> 

                            public Son ()
                            home = new Shack();





                            You can check if the home field has the correct type (and also not null) with a simple test:



                            public class SonAndDadTest 

                            @Test
                            public void sonTest()
                            Son son = new Son();
                            Assert.assertNotNull(son.getHome());
                            Assert.assertEquals(son.getHome().getClass(), Shack.class);


                            @Test
                            public void dadTest()
                            Dad dad = new Dad();
                            Assert.assertNotNull(dad.getHome());
                            Assert.assertEquals(dad.getHome().getClass(), Building.class);









                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 27 at 10:21









                            LoreloreloreLorelorelore

                            2,3386 gold badges19 silver badges29 bronze badges




                            2,3386 gold badges19 silver badges29 bronze badges






























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374455%2foverride-class-parameter-type-in-java%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해