Results 1 to 5 of 5
Thread: Getters and Setters
- 11-01-2009, 11:06 AM #1
Member
- Join Date
- Nov 2009
- Posts
- 2
- Rep Power
- 0
Getters and Setters
Absolutely new to Java. :c Introduced to Eclipse a few weeks back, and I'm getting really confused with the Strings class.
Anyone care to post how getters and setters are used with doubles? Say I want to make a simple program where the user inputs a length and height, and using getters and setters, the program computes for the area of a rectangle?
And, much as I want an alternative to the get/set fields(?), it won't be of much help at the moment.
Thank you so much <3
- 11-01-2009, 03:53 PM #2
a double is a data type, getters and setters would work like:
Java Code:/** *Created on Nov 1, 2009 */ public class ComputeArea { double width; double height; public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } /** * Computes the area (width * height). * Should be called after the setWidth() and setHeight(). * @return */ public double getArea() { return this.width * this.height; } public static void main(String[] args) { ComputeArea compute = new ComputeArea(); Scanner scanner = new Scanner(System.in); System.out.print("enter width: "); compute.setWidth(scanner.nextDouble()); System.out.print("enter height: "); compute.setHeight(scanner.nextDouble()); System.out.println("area=" + compute.getArea()); } }
- 11-01-2009, 04:15 PM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Whole idea about the getter/setter methods are hiding the implementation. And at the same time, avoid the conflict with outside access in future developments. If you can read about that it's much better at the same time. I guess you've no much better idea about those. Sorry pal, I cannot post links to you, because you are not able see them yet. So please search on the google. Good luck! :)
- 11-01-2009, 11:47 PM #4
Member
- Join Date
- Nov 2009
- Posts
- 2
- Rep Power
- 0
I actually got mine to work before reading this, but your example was ten shades of helpful and then some. <3 Hee, thank you~
I keep getting confused with the String class o:
- 11-02-2009, 01:47 AM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Similar Threads
-
[SOLVED] Problem with program(getters/setters,arrayList).
By Pierced1 in forum New To JavaReplies: 1Last Post: 02-19-2009, 03:50 AM -
Getters and Setters
By Charliestons in forum New To JavaReplies: 10Last Post: 09-12-2008, 10:57 PM -
How To Add Fields And Generating Getter-Setters
By JavaForums in forum NetBeansReplies: 0Last Post: 07-30-2007, 11:13 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks