Solved

Java Constructor and Getter and Setter Methods

Posted on 2013-01-03
5
943 Views
Last Modified: 2013-01-03
Hello

I have a quick question regarding Java Constructor and Getter and Setter Methods.

Do you have to declare and  initialize both a constructor and getter and setter methods in your class. Or can you choose one or the other?

Thanks
0
Comment
Question by:Kevin_Coors
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 16

Accepted Solution

by:
krakatoa earned 255 total points
ID: 38742179
You don't need any of them if you don't want to.

You "get" a default constructor from the JVM when you instantiate a class object. Obviously the default ctr is not retro-fitted into your code - you don't see it, it just gets implemented. Getters and Setters are to adhere to OOP principles, whereby you should have only private variables in a class, and have them interrogated and modified by other class objects via method calls, so as not to create dependencies.
0
 

Author Comment

by:Kevin_Coors
ID: 38742207
Hey Krakatoa

Sorry, If the class variables are private I mean.

I know how to use the dot  notation to  call a class variable i.e. var.name = "John" but I have read that this is poor practice for encapsulation.

Does Encapsulation require a constructor followed by getter and setter methods?
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38742241
but I have read that this is poor practice for encapsulation.
Depends who you ask I reckon. Dot notational access implies leaving the back door open for anyone who wants a cup of sugar. Getter method will pass you the sugar through a hatch.

See this.
0
 

Author Comment

by:Kevin_Coors
ID: 38742264
great website!

thanks again
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38742271
Cool.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is an explanation of a simple data model to help parse a JSON feed
This is about my first experience with programming Arduino.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Six Sigma Control Plans

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question