• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Passing a class type variable to a method - in need of clarification

 
Rancher
Posts: 115
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I am new to Coderanch, and a 3 month beginner with Java.

I need a little clarification. The top code is class Point. It is used to calculate the distance between two points.  On line 24 I created a method distance(Point secondPoint) so that I could call this method from my main method which is presented below the class Point.  Since originally I only had the no-parameter distance() and the 2 parameter distance(int x, int y) methods. My code worked fine when I called the 2 parameter distance method by plugging in the values when creating the objects first and second, and even updating them with setx() and setY(). But, when I wanted to calculate the distance between first and second  using the first.distance(second) call IntelliJ gave me an error, but thankfully with a suggestion -  "create method 'distance' in 'Point'". So I did, and got it to work.  

From my point of view, what I am doing on line 24 is creating a variable named secondPoint of type Point (a class variable) that can be anything that I want, and in this case a reference to another point. Am I correct in this assumption?  

Is this called something specific in java besides passing an object of class type to a method? I would like to read more on this.

Lastly, why do I have to create a variable of type class? What is it about the class type variable that makes this code work?

Thanks





public class Main {
   public static void main(String[] args) {

       Point first = new Point();

       Point second = new Point();

       first.setY(6);
       first.setX(9);

       second.setX(12);
       second.setY(3);

       System.out.println("distance from point 'first' to point 'second = " + first.distance(second));

   }
}

 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

I think that conceptually, you understand what's going on just fine, you're just using the wrong terminology.

Point is not a class variable. It's a class. secondPoint is a variable of type Point, meaning it can hold references to instances of type Point.

You can not assign just anything to secondPoint. Only references to Point objects or references to objects that are a subtype of Point. You can not assign a Triangle to a variable of type Point.

I don't really understand your question "What is it about the class type variable that makes this code work?". What alternative did you think would work that didn't?
 
bryant rob
Rancher
Posts: 115
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Stephan,

Thanks for the reply. Ok, I have a couple additional questions so please bear with me:

secondPoint is a class variable of type Class; This I understand, sorry for my wording below, but this I get.


So, secondPoint can only reference objects that I create that are instances of a Point....and in my case actual points represented by (x,y) coordinates. (i.e. Point 1(3,5) Point 2(8,6) Point(5,3) and so on).  

What I should have done is once I created my method distance(Point second); with the help of IntelliJ Idea (thank goodness for IntelliJ Idea or I would have been lost as can be)  went back and changed my variable 'second' name to anyPoint. Now any object I create for a Point (i.e (3,5)) I can now pass to first.distance(anyPoint) and this in my opinion is more readable and easier to understand. Because all I am trying to do here is be able to compare as many points as I want by creating objects for each.  And, the only way to use this variable anyPoint is for it to be a place holder for any other object I create of type Point. Meaning I can't actually state somewhere in my code:

Point thirdPoint = new Point();

Point anyPoint = thirdPoint;

Am I close so far??


Lastly, could you please provide me an example of how I could do this with a subtype of Point?

Thanks.







 
Stephan van Hulst
Saloon Keeper
Posts: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

bryant rob wrote:secondPoint is a class variable of type Class


No. secondPoint is just a variable, not a "class variable". Java has a different concept that your phrasing could be confused with, but you're not there yet. Also, the variable is not of type Class. It is of type Point, and point is a class.

So, secondPoint can only reference objects that I create that are instances of a Point....and in my case actual points represented by (x,y) coordinates. (i.e. Point 1(3,5) Point 2(8,6) Point(5,3) and so on).


Yes.

Meaning I can't actually state somewhere in my code:

Point thirdPoint = new Point();

Point anyPoint = thirdPoint;


Why wouldn't you be able to do that?

Lastly, could you please provide me an example of how I could do this with a subtype of Point?


Point is a bit of a bad example to do this. It doesn't make a lot of sense to subclass a point in 2D space.

Are your reading the Java tutorials? You'll run into subclassing and inheritance soon enough.
 
bryant rob
Rancher
Posts: 115
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the clarification. You have cleared up a lot for me. Actually I am taking the Java Masterclass by Tim Buchalka on Udemy. I'm almost 100 modules in, and there are a little over 300 total.  I have went through two sections that contain modules on inheritance, encapsulation, composition, and polymorphism, but now am going back over each module in the sections to try and get a better understanding on these topics.

I have found that once I complete a module and work the exercises, I believe I understand what is going on, but when introduced to a new topic my understanding seem to muddled in the process and I lose my confidence. So by going back over each section until I have a good understanding  and can repeat the coding exercises based on understanding the material without having to look at the solution, I then change the code up and try to get all twisted up so that I can problem solve the situation and work my way out of it. I'm not sure if this is the way I should be doing it but it is the only way that I have been successful at learning anything.

I am working my way back through inheritance at the moment, and actually working on a complex number problem, and it seems that one of the ways of solving that problem involves the technique of creating a variable of type ComplexNumber just as I created a variable of type Point in the Point exercise.  So, I was able to solve that part of the problem with no problem. I still needed a little help solving a couple other things but I was able to overcome those issues searching the web. I try not to ask on any forum until after I have exhausted all other options. I find that I learn so much more by searching the web and googling. The only problem is I spent almost 10 hours before posting on here.  My wife thinks I'm crazy.

Hey, all I know is that I am loving this stuff. I wish I had done this years ago.

Thanks again.
 
 
Stephan van Hulst
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's great that you are driven. You'll get there eventually.

I have some comments on the design of the Point class. It's not about what you CAN do, it's about what you SHOULD do.

Your Point class contains setters for the x and y fields. While setters are unavoidable in some cases, for many types they are actually harmful.

When you think about the points (2, 3) and (4, -1) in 2D coordinate space, you think of them as two fixed objects, right? "Setting" the x coordinate of (2, 3) to 1 doesn't really make sense. Instead, you just think about a new point with coordinates (1, 3).

The reason it's harmful is because you might pass an instance of type Point to another object that assumes that the point will never change. Then when you do change the coordinates of the point, the object that depends on the Point will have been corrupted.

Secondly, use names that are as descriptive as possible. A distance() method without parameters didn't make sense to me until I looked at the implementation. Methods should be clear in their purpose without having to look at their implementation.

Override the toString() method if you can to give your objects a good textual representation for debugging. Override the hashCode() and equals() methods if your class represents a value type: Objects of a value type represent a fixed value that can be compared to another object of the same type, such as the number 7.3, the character 'K' or the point (4, 2). Your Point class is an ideal candidate if you drop the setters.

Make your classes and members as private as possible. Lose the habit of writing public everywhere. Only raise the visibility of a class or method if you really need it outside of the package or class you declared it in.

Make your classes final. This prevents them from being subclassed. Subclassing is a powerful tool, but it comes with a lot of unforeseen challenges that are hard to deal with if you haven't carefully designed your class. The easiest thing is to just prevent it.

Here's an updated version of your class.
 
bryant rob
Rancher
Posts: 115
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Stephan thanks for the info. I really do appreciate it. I am very interested in doing things the best way from the beginning, like practicing good coding. I have even ditched the mouse to a large degree and am learning the keyboard shortcuts. One thing I will note is I can't seem to find an up to date good coding practices on the order of where everything should be in my code. I like my methods with calculations (i.e. distance()) at the top following the constructor, then the getters. IntelliJ will invariably put it after the getters. Is there a defined good coding practice as to this?

As far as:

The setters: I wondered why the instructor left them out, but I added them because I wanted flexibility, but now I see why this could led to a problem. So, in the future, I will use them only if necessary.

The toString(), hashCode(), and equals() methods: I am approximately 50-60 modules from that point.  Thanks for bringing these to my attention because I will start to use these in my code early when necessary. That is a great thing about self learning, I'm not limited.

Private versus Public: The instructor hasn't really dove deep into this area. Sometimes he provides examples of each in the code. I have played around with these as well as written code with protected, and no modifier to test what was accessible and from where.

When I am finished with the section I am on I am going to dissect your version, compare it to mine and try to learn what you did.

Thanks again.
 
Stephan van Hulst
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't think there's really a standard guide for member ordering.

For personal projects, I prefer this order:

  • static fields
  • fields
  • simple nested classes/interfaces/enums
  • constructors
  • static factory methods
  • simple properties (getters/setters)
  • calculated properties
  • other instance methods
  • other static methods
  • other nested (private) classes

  • I don't follow this list religiously though. What works well for one class may not work for another.

    What's important is to be consistent, but not draconian.

    And as always, if you're working for a company that prescribes One True Way of doing things, you suck it up and do what they tell you to.
     
    bryant rob
    Rancher
    Posts: 115
    9
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks.
     
    Saloon Keeper
    Posts: 27762
    196
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Here you go:

    Class Point is of type Class, but an object (instance) of class Point is of type Point.

    Class Class is also of type Class, and an object of class Class is of type Class.

    And, of course, all object instances are of type Object including object of class Class - and class Point - thanks to inheritance rules in Java.

    And if that doesn't make sense Let me commend you to the White Knight in Lewis Carroll's works. Carroll, in his alter ego of Charles Lutwidge Dodgson wrote several books on mathematics and logic besides his Alice books.
    reply
      Bookmark Topic Watch Topic
    • New Topic