Java - How to define a parameterized constructor? - constructor

Java - Define a parameterized constructor for the Circle class that when passed one integer parameter, copies it into the radius instance variable.
Test Input Result
Circle r = new Circle (10); Parameter is 10 10
System.out.println(r.radius); Parameter is 3456 3456
Class Circle {
public int radius;
//PLEASE HELP ME HERE
}
Very basic question I guess, I'm new to programming. Thank you so much for helping me!

Related

Can you help me make sense of this class constructor? (Adafruit_ATParser)

I am building a device for my research team. To briefly describe it, this device uses a motor and load sensor connected to an Arduino to apply a rotational force to a corn stalk and record the resistance of the stalk. We are in the process of building Bluetooth into the device. We are using this BT module.
We have a BLE GATT Service with 2 characteristics for storing DATA and 1 for holding the command which is an integer that will be read by the device and acted on. Reading the command characteristic is where we encounter our problem.
void get_input(){
uint16_t bufSize = 15;
char inputBuffer[bufSize];
bleParse = Adafruit_ATParser(); // Throws error: bleParse was not declared in this scope
bleParse.atcommandStrReply("AT+GATTCHAR=3",&inputBuffer,bufSize,1000);
Serial.print("input:");
Serial.println(inputBuffer);
}
The functions I am trying to use are found in the library for the module in Adarfruit_ATParser.cpp
/******************************************************************************/
/*!
#brief Constructor
*/
/******************************************************************************/
Adafruit_ATParser::Adafruit_ATParser(void)
{
_mode = BLUEFRUIT_MODE_COMMAND;
_verbose = false;
}
******************************************************************************/
/*!
#brief Send an AT command and get multiline string response into
user-provided buffer.
#param[in] cmd Command
#param[in] buf Provided buffer
#param[in] bufsize buffer size
#param[in] timeout timeout in milliseconds
*/
/******************************************************************************/
uint16_t Adafruit_ATParser::atcommandStrReply(const char cmd[], char* buf, uint16_t bufsize, uint16_t timeout)
{
uint16_t result_bytes;
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
// Execute command with parameter and get response
println(cmd);
result_bytes = this->readline(buf, bufsize, timeout, true);
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
return result_bytes;
}
None of the examples in the library use this. They all create their own parsers. For example, the neopixel_picker example sketch has a file called packetParser.cpp which I believe retrieves data from the BT module for that specific sketch, but it never includes or uses Adafruit_ATParser.. There are no examples of this constructor anywhere and I cannot figure out how to use it. I have tried these ways:
bleParse = Adafruit_ATParser();
Adafruit_ATParser bleParse();
Adafruit_ATParser();
ble.Adafruit_ATParser bleParse();
note: ble is an object that signifies a Serial connection between arduino and BT created with:
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
Can anyone give me a clue on how to use the Adafruit_ATParser() constructor? Also, if the constructor has no reference to the ble object, how does it pass AT commands to the BT module?
I know this is a big ask, I appreciate any input you can give me.
Like this
Adafruit_ATParser bleParse;
You were closest with this one Adafruit_ATParser bleParse();. This is a common beginner mistake because it looks right. Unfortunately it declares a function bleParse which takes no arguments and returns a Adafruit_ATParser object.
I can't answer the second question.
EDIT
I've taken the time to have a look at the code. This is what I found
class Adafruit_BluefruitLE_UART : public Adafruit_BLE
{
and
class Adafruit_BLE : public Adafruit_ATParser
{
what this means is that the Adafruit_BluefruitLE_UART class is derived from the Adafruit_BLE class which in turn is derived from the Adafruit_ATParser class. Derivation means that any public methods in Adafruit_BLE can also be used on a Adafruit_BluefruitLE_UART object. You already have an Adafruit_BluefruitLE_UART object (you called it ble) so you can just use the method you want to use on that object.
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
ble.atcommandStrReply( ... );

Do function arguments violate encapsulation?

This question is related to OOP practice in general.
Say we have a class with a public function accepting passed in arguments from outside of the object. Is that not a violation of encapsulation in itself? On the other hand why is this practice used so widely? After all the constructor of the class and member variables are kind of "by-passed" when calling the function. As an relatively new programmer to OOP and my understanding of encapsulation my function parameters are passed into the object through setters, so that I keep all of my functions without any arguments using the passed in member variables only.
I know that certain arguments can be passed in through the constructor (BTW, I use dependency injection), but what if those parameters change after the object is being instantiated? There must be a way to change those values after the object is created. So far I found no other option than using setters to accomplish this task, but there is a long lasting discussion among programmers about getters and setters to be "evil" or at least considered no good programming practice.
Can anyone tell my where I missed the point and how to solve this dilemma in a clean way?
Many thanks in advance for any support.
Here is a concrete very simple example using C#:
we have a form in a windows form project holding 3 textboxes ,named textBox1 and textBox2 and textBox3.
The task is to add values of textBox1 and textBox2 and returning the result to textBox3 using class AddTextboxValues instantiated by event handler any time the value of textBox1 or textBox2 changes:
The way I see it often and ask if is violation of encapsulation:
public class AddTextBoxValues
{
public double TextBoxValueSum(double textBox1value, double textBox2Value)
{
return textBox1value + textBox2Value;
}
}
This is the way I use at the moment as per my understanding of encapsulation:
public class AddTextBoxValues
{
private double textBox1Value;
private double textBoxValue2;
private double textBoxValue3;
public double TextBox1Value
{
set { textBox1Value = value; }
}
public double TextBoxValue2
{
set { textBoxValue2 = value; }
}
public double TextBoxValue3
{
get { return textBoxValue3; }
}
public void TextBoxValueSum()
{
textBoxValue3= textBox1Value + textBoxValue2;
}
}
This has also the advantage that it can be injected into the form constructor.
Any comment is highly appreciated.
Thank you very much Jon Skeet, you are a real professional.
You diagnosed my problem exactly and opened my eyes for the lack of knowledge to understand and find a solution to my own question. It was indeed a deeper understanding of encapsulation and "object state" which built the missing piece of my puzzle.
Everything seems logic and clear now for me and I hope it will help others in the future,too.
Both examples are not object oriented programming. They are examples of procedural programming.
First "class" is, in fact, just a namespace wrapping TextBoxValueSum function.
Second "class" is just a structure with public fields (there is no difference between getters-setters and public fields).
If you want to use real object oriented programming, you should think of objects, that they are representation of things.
In your case, I'd write class Sum which is a real thing that represent one, specific sum:
class Sum {
private double a, b;
public Sum (double a, double b) { this.a = a; this.b = b; }
public double value() { return this.a + this.b; }
}

calculation under class as3

I am absolutely a beginner in as3; I am really trying to understand how as3 works. I wrote a simple function which will multiply one number (please see the following code). I want to multiply 9 with 5 and trace it but it's not multiplying. Can anyone help me?
package {
import flash.display.MovieClip;
public class main extends MovieClip {
var xyz:int=9;
public function main() {
// constructor code
mAth(xyz);
trace(xyz);
}
protected function mAth(xyz:int):int{
return(xyz*5);
}
}
}
You call the function "mAth" but don't use the results. try
trace(mAth(xyz));
to see the results of the function call.
Is there a specific reason why you pass an internal variable to a function? You can access xyz without passing the value to the mAth function.
It's a correct answer overall but it's not the main reason why trace is not showing the expected results and since the user wants to understand the given answer does not supply a why to a perfectly valid operation.
Here is a better one:
Primitive objects in AS3 are passed by value not by reference. Those are numbers and strings. When you pass your variable xyz to your function you would expect it to be modified like in some other language but since only the value it represents is passed your variable is not modified and stay at 9. This is the default behavior of AS3 and it cannot be overridden. So you just have to remember that primitive objects in AS3 when passed as parameters in methods/functions are only passed by value and as a result do not see their value change.
in your case:
var xyz:int=9;
var result:int = mAth(xyz);
//xyz is still 9 since only its value is passed to the method
//result is 45 since it computes and return the value passed as parameter

Weird behavior of Red5 service parameters called from Actionscript

I have a Red5 service function that receives a single string as a parameter, and another function that takes no parameters, like the code below:
public class AService
{
private String someName;
public void setName(String aName)
{
someName = aName;
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
I also have an ActionScript function that calls the service function, using the dynamic parameter:
public class Connector
{
private var netConn: NetConnection;
public function invokeCall(theFunc:String,...theParams): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
.
.
}
I am aware that the "...theParams" is actually an array of parameter objects. I also know that the NetConnector class' call() method uses that parameter object array. Unfortunately, when I do an invokeCall() on my service's makeMessage() method (without putting in a parameter) like so:
invokeCall("AService.makeMethod");
I get a function nonexistent message from Red5. The only way I can make it work is to create two invoke methods, one with parameters and one without, and call that function without parameters.
Furthermore, calling my setName() function, like so:
invokeCallwithPrams("AService.setName","factor3");
doesn't seem to work unless I change the signature of my service function:
public class AService
{
private String someName;
public void setName(String[] aName)
{
someName = aName[0];
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
which I don't mind (even though the Red5 documentation indicates that I shouldn't have to treat the parameter as an array), except that when I pass the string "factor3" into the NetConnection class' call() method, somehow it becomes "[factor3]" in setName()!
Obviously, something is screwy here, but I haven't been able to figure it out.
I am using Red5 Version 1.0.1 and my Actionscript is Version 3.
Can anyone explain to me what is going on and (more importantly) how to fix this???
If so, please advise...
UPDATE: The weirdness continues
I did a test in which I changed the parameter of the function I used to set up and invoke the NetConnection class' call() method. Instead of passing it a "...theParams", I changed it to theParams:String, like so:
public function invokeCall(theFunc:String,theParams:String): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
Interestingly, the brackets that appear in my service method setName() go away!
Whatever this problem is, it has something to do with the dynamic parameters in Actionscript. I suspect that I have found a bug in Actionscript 3 that does not allow it to properly handle dynamic parameters that are passed to a method from another method.
Has anyone else seen this problem? Is there any solution? The dynamic parameters are supposed to allow anyone to add parameters as necessary and make them any object that is necessary. Unfortunately, it doesn't look like you can use dynamic parameters passed from another method without them being screwed up.
This looks like a serious bug in Actionscript. Am I correct?
Someone please advise...
I found the solution. It is not a bug in Actionscript, it is a bit of strangeness in the language.
The basic information about the solution can be found here:
AS3 variable length argument expand to call another function with var length args
Based on what is there, I needed to do the following in the method I am using for invokeCallwithParams:
.
.
var conn:Connector = new Connector();
private function invokeCaller(fName:String,...cParams)
{
cParams.unshift(fName);
conn.invokeCall.apply(conn,cParams);
}
This eliminates the unnecessary brackets passed into my setName() service function, meaning that I can pass dynamic, variable length parameters from one method to another...

Strongly typed collection with multiple base types in ActionScript (Vector <T,T>)?

Does ActionScript have any way of handling a strongly typed list with multiple base types?
I am actually looking for something such as a Vector<T,T> ?
Is it possible?
Or is the only way of doing it is creating my own class which accepts lets say a String and Number in the constructor and create a Vector<T> out of that class?
No, not by standard. If the items are not one of the primative types you can build a Vector of interfaces, or super classes. For example, a vector of DisplayObjects that contain a mixture of MovieClips and Sprites (which both inherit from the DisplayObject).
For example:
var v:Vector.<DisplayObject> = new <DisplayObject>[
new MovieClip(),
new Sprite(),
new MovieClip()
];
trace(v[0].alpha); // outputs 1
trace(v[0].currentFrame); // error - not a DisplayObject property
In this case the vectors item will only expose the properties and methods of itself that stem from the Vectors type. But this is exactly the reason you should use vectors, it ensures the items type you are handling.
I don't know your specific case or goal, but I would consider why you need a mixed type within a vector. Your alternative option, as you stated, would be to create a wrapper class. The example below is far from complete but a starting point.
class Wrapper {
public var _value:*; // should be private with get/set's
public function Wrapper(value:*) {
if(value is String || value is Number) {
_value = value;
}
}
}
You can't do that, so I would go with your suggestion, which is to create a special class containing two properties (say Number, String) and create a Vector of that.