Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java Queries

Options
  • 05-05-2016 11:25pm
    #1
    Registered Users Posts: 8,166 ✭✭✭


    Hi,

    I'm working my way through an online Java tutorial. So far, most of it is okay and I understand the concepts and rationale. However I've got a few queries that are probably very basic.

    1. I've been through the tutorial on constructors. There was no mention of deconstructors. A quick online trawl seems to show that the garbage collection feature of Java handles this. Does this do it fully, or are there any aspects of it that I need to be aware of?
    2. Why are constants final and static? I understand that final means that it is its final value. Show what does the static keyword add to things?
    3. What is the use of interfaces? From the examples it seems you have to implement the method fully in each class. I can't see what the benefit would be for a programmer. Can someone explain?
    4. I'm lost on Polymorphism. What is it and how does it differ from method overloading? I've looked at a number of online resources and it still confuses me. Can anyone please help me on this?
    5. Downcasting. If it is inheritedly unsafe, is it used and/or is it good practice to avoid downcasting?


    Thanks.


Comments

  • Registered Users Posts: 1,148 ✭✭✭punk_one82


    Garbage collection handles cleaning up objects. It's unpredictable and you can't even be sure it will happen at all for certain objects. There's a finalize() method that gets called just before the garbage collector does it's job, so if there's any cleaning up then it would be put in there but you can't guarantee it will ever be called.

    If a constant is not static then Java will allocate memory for it in every object created for that class. If it's static there will only be one copy per class.

    Interfaces define a contract for functionality that can be implemented in multiple ways. Say you have a Shape interface. You can define a method in that interface called getArea(). You can then implement the Shape interface for Square, Rectangle, Triangle etc. They all have their own implementations of getArea(). They also offer a level of abstraction when you're programming which is why people follow the term "programming to an interface" as best practice. If you have multiple Square, Triangle, Rectangle objects and you want to iterate through each one and calculate the area, if they've implemented a Shape interface then you don't need to know specifically what type of shape it is you're looking at, you can just write Shape myShape = getNextShape() and on myShape you can call myShape.getArea().

    Polymorphism as the name suggests means things can take another form. Method overloading is a form of polymorphism. You can have multiple methods in the same class with the same name but different return types/parameters. Another form of polymorphism(LOL) is method overriding. Say you have Bicycle class with some methods like getNumberOfGears or hasBell. The parent class can implement those methods as appropriate for your standard bicycle. You can then extend that class and create RacingBicycle. For RacingBicycle you can override the methods getNumberOfGears and hasBell and give them the appropriate implementations for a RacingBicycle object.

    For the most part you don't want to downcast unless it's absolutely necessary. It's not something I see regularly if ever.

    Edit: Apologies if my reply is all over the place. Severely hungover in work.


  • Registered Users Posts: 6,251 ✭✭✭Buford T Justice


    Also, if a variable is declared as static, then it is available outside an instance of a class.

    For example, a class level non static variable would / could be accessed by:
    new myClass().varName;
    

    whereas if its static you can call it as follows
    className.varName;
    

    Declaring a variable as final means that once you assign a value to the variable it cannot be changed for the lifecycle of the application.


  • Registered Users Posts: 8,166 ✭✭✭funkey_monkey


    Thanks for the replies.

    I'm still a bit unsure about polymorphism, I can't seem to figure out the difference in the definitions online between polymorphism and method overloading. Can someone please break it down a bit more for me?
    Is polymorphism = method overriding?

    Are the following all types of polymorphism?
    • function overloading
    • operator overloading
    • parametric polymorphism
    • multiple dispatch
    • double dispatch
    • single and dynamic dispatch
    • subtyping
    • virtual function

    Is it a must to know all of these to be a proficient Java programmer or are some of them really only taught but not used in industry?


  • Registered Users Posts: 8,166 ✭✭✭funkey_monkey


    Done some more reading over on stackoverflow and they can't seem to agree on a definition either :(


  • Registered Users Posts: 8,166 ✭✭✭funkey_monkey


    More questions.

    Anonymous classes
    class Machine(){
       public void start(){
          System.out.println("Machine is starting.");
       };
    }
    
    public class app(){
    
       public static void main(){
    
          Machine Machine1 = new Machine(){
             @Override
             public void start(){
                System.out.println("Camera is starting.");
             }
          }
       machine1.start();
       }
    }
    



    >>> Output = Camera is starting.
    • Why is the start() used to ouput to the console callsed an anonymous class, is it not a method? Or have I missed what the anonymous bit really is?
    • If I then define a new machine as Machine Machine2 = new Machine(); i.e. no override, then the console output will be >>> Machine is starting. Correct? (Sorry, not got set up with an IDE yet!).


  • Advertisement
  • Registered Users Posts: 1,148 ✭✭✭punk_one82


    You don't need an IDE. I'd highly recommend getting a decent text editor, getting the JDK set up on your machine and writing/compiling/running this code yourself. You'll start to see what's going on.


  • Registered Users Posts: 778 ✭✭✭pillphil


    More questions.

    Anonymous classes
    class Machine(){
       public void start(){
          System.out.println("Machine is starting.");
       };
    }
    
    public class app(){
    
       public static void main(){
    
          Machine Machine1 = new [B]Machine(){
             @Override
             public void start(){
                System.out.println("Camera is starting.");
             }
          }[/B]
       machine1.start();
       }
    }
    



    >>> Output = Camera is starting.
    • Why is the start() used to ouput to the console callsed an anonymous class, is it not a method? Or have I missed what the anonymous bit really is?
    • If I then define a new machine as Machine Machine2 = new Machine(); i.e. no override, then the console output will be >>> Machine is starting. Correct? (Sorry, not got set up with an IDE yet!).


    Not a programmer, but as I understand it:
    1. the bit I have bolded is the anonymous class. You have extended the machine class and overridden the start method and assigned this object to a variable of it's parent class (I assume anonymous is because you haven't given the new class a name)
    2. Yes, if you instantiate another machine and call it's start method, it will produce "Machine is Starting". The anonymous class is used when you only need to use the class once.


    There are a few mistakes in your program but I expect that's due to not having a compiler.
    +1 on a text editor, there are also lots of online compilers for java if you're stuck, here's one at random
    http://www.tutorialspoint.com/compile_java_online.php


  • Registered Users Posts: 1,463 ✭✭✭Anesthetize


    punk_one82 wrote: »
    You don't need an IDE. I'd highly recommend getting a decent text editor, getting the JDK set up on your machine and writing/compiling/running this code yourself. You'll start to see what's going on.
    I'd disagree with this somewhat. If somebody's new to Java I'd highly recommend installing an IDE such as Eclipse or NetBeans and learning how to use the debugger tool. You'll learn a lot about how code works by stepping through it using the debugger and observing what happens. Debugger is your friend :)

    Text editors such as Notepad++ or Gedit are great for quick changes, or for scripting languages such as Bash. But learning Java would be more difficult and frustrating without an IDE.


  • Registered Users Posts: 1,148 ✭✭✭punk_one82


    I'd disagree with this somewhat. If somebody's new to Java I'd highly recommend installing an IDE such as Eclipse or NetBeans and learning how to use the debugger tool. You'll learn a lot about how code works by stepping through it using the debugger and observing what happens. Debugger is your friend :)

    Text editors such as Notepad++ or Gedit are great for quick changes, or for scripting languages such as Bash. But learning Java would be more difficult and frustrating without an IDE.

    Just to clarify, I wasn't advocating the use of a text editor over an IDE. Just suggesting a quick and easy way of writing and compiling code. Using an IDE and debugging is a great way to learn.


  • Registered Users Posts: 778 ✭✭✭pillphil


    I'd disagree with this somewhat. If somebody's new to Java I'd highly recommend installing an IDE such as Eclipse or NetBeans and learning how to use the debugger tool. You'll learn a lot about how code works by stepping through it using the debugger and observing what happens. Debugger is your friend :)

    Text editors such as Notepad++ or Gedit are great for quick changes, or for scripting languages such as Bash. But learning Java would be more difficult and frustrating without an IDE.

    It helps hammer the basics home when you're starting though. Nothing like writing
    public static void main (String[] args)
    
    fifty times to make sure you don't forget it.

    I learned Java using a text editor, so I know the basic layout for a class, I learned C# with visual studio and so I can never remember the basic layout. I disagreed with the text editor format at the time, but in retrospect, I think it was a good idea.


  • Advertisement
  • Registered Users Posts: 6,136 ✭✭✭Talisman


    Thanks for the replies.

    I'm still a bit unsure about polymorphism, I can't seem to figure out the difference in the definitions online between polymorphism and method overloading. Can someone please break it down a bit more for me?
    Is polymorphism = method overriding?

    Are the following all types of polymorphism?
    • function overloading
    • operator overloading
    • parametric polymorphism
    • multiple dispatch
    • double dispatch
    • single and dynamic dispatch
    • subtyping
    • virtual function

    Is it a must to know all of these to be a proficient Java programmer or are some of them really only taught but not used in industry?
    Polymorphism isn't really one particular thing that you learn, it is a concept that reflects the biological principles of something taking on one or more forms. In programming, it simply means the overloading or overriding of functions and the declaration of objects using inheritence.

    Overloaded Functions:
    A function does something, an overloaded function should do the same thing but with a different signature. i.e. an overloaded function will take different parameters.

    Function Overriding:
    You have a parent class with a particular function and you want the child class to have the same function but with a slightly different implementation.

    Everything in your list is related to polymorphism.
    • function overloading
      See above.
    • operator overloading
      Operator overloading is a specific case where different operators have different implementations depending on their arguments.
    • parametric polymorphism
      This is just another term for Generics in Java. Generics FAQ
    • multiple dispatch
      Multiple dispatch is a type of polymorphism where multiple parameters are used in determining which function to call.
    • double dispatch
      Double dispatch is a special case where the function to call is dynamically determined by the class of the two objects involved. For example in an event handling system, both the event type and the type of the object receiving the message will determine the correct function to handle the event.
    • single and dynamic dispatch
      Single dispatch is a type of polymorphism where only one parameter is used to determine the function to call. You use this all the time when you call a function in a class, e.g.
      className.methodName();
      

      Dynamic dispatch is the run-time decision mechanism by which a call to a function is resolved.
    • subtyping
      Subtyping is inheritence and without inheritance there would be no polymorphism.
    • virtual function
      A virtual function is a function whose behaviour can be overridden in an inheriting class by a function that has the same signature.

    If you are having difficulty with Object-Oriented concepts such as Polymorphism and Interfaces, I would suggest reading Practical Object-Oriented Design in Ruby by Sandi Metz. Don't let the fact that it's a Ruby book put you off, it will teach you Object-Oriented Design. Some college student uploaded it to their Github account so you don't have to buy it.


  • Registered Users Posts: 16 niall300


    polymorpism (many forms) is essentially inheritance. A BMW is a CAR is a VEHICLE. The BMW can be treated as a generic Car or even a generic vehicle. So I can tell my collection of vehicles to start without having to worry whether these vehicles are Cars or Motorbikes. I am treating my BMW polymorphically as a vehicle. So the base class is Vehicle (technically the base class for everything is actually object but don't worry about that for now)which is inherited by Car which is inherited by BMW. If you want to go in to more detail, I would suggest youtube tutorials. hope this helps


  • Registered Users Posts: 778 ✭✭✭pillphil


    Is a bicycle a vehicle? Can you start one? :p


  • Registered Users Posts: 16 niall300


    O.K. BMW is a CAR is a MOTOTISED_VEHICLE (will that do?) :D


  • Registered Users Posts: 871 ✭✭✭moycullen14


    niall300 wrote: »
    O.K. BMW is a CAR is a MOTOTISED_VEHICLE (will that do?) :D

    What about a BMW motorbike? :eek:

    The only thing you have to remember about OO concepts is this:

    What is Daisy? Is she a cow?
    No, Daisy is an instance of a cow!


  • Registered Users Posts: 121 ✭✭DefinitelyMarc


    Head first Java has a sample chapter in this very subject. I'd link, but I'm a new user.

    100% legal, they offer you the second and eighth chapter for free, out of about sixteen I think. Just google O' Reilly head first Java and there's be a link in the sidebar.

    It's a good book, so count yourself lucky!

    Edit: Here you go


Advertisement