class object definition - programming jargon: - language-agnostic

what's the definition of class object that has more than one version?
what's the name of object like that that has a default and than versions with more parameters?
say you have it like that:
public class object
{
public object()
{
get sth; do sth;
}
public object(k)
{
get sth with k; do sth with k;
}
public object(k, n)
{
get sth with k; do sth with k;
get sth with n; do sth with n;
}
}

Related

I want the integer that was asked to the user to go to the Cat class so it outputs the word "meow" until the counter is equal to the number

This is the main method.
I want the integer that was asked to the user to go to the Cat class so it outputs the word "meow" until the counter is equal to the number
import java.util.Scanner;
public class Runnable {
**public static void main( String args[]) {
Scanner input = new Scanner(System.in);
Cat cat1 = new Cat();
System.out.print("Enter num :");
int num.sound()=input.nextInt();
System.out.println("Calling method with no parameters");
cat1.sound();
System.out.println("Calling method with one parameter");
cat1.sound();
}
}
this is a Class called Cat
public class Cat {
public void sound() {
System.out.println("Meow");
}
public void sound( int num){
int counter=0;
for(int num1=counter; num1>=num; counter++) {
System.out.println("Meow");
}
}
}
A couple of things first:
what you mean with the line:
int num.sound()=input.nextInt();
you not pass paramenters in
System.out.println("Calling method with no parameters");
cat1.sound();
System.out.println("Calling method with one parameter");
cat1.sound();
But the main flow is in the for loop that could be:
for (int num1 = 0; num1 < num; num1++)
{ ... }

changing fieldName of Json twice

Is it possible to change Json field name two times in Spring rest api. I know it is not very meaningful but I need something like this.
For example the json which I am getting from the remote service is
{
total_count : 1;
}
My Model class is like
public class Model
{
#JsonProperty("total_count")
int count;
}
And from my rest service I want to return a json of Model class but with the field "count" instead of "total_count"
{
count: 1
}
Is that possible to do something like this?
Try something like:
public class Model {
int count;
#JsonGetter("count")
public int getCount() {
return count;
}
#JsonSetter("total_count")
public void setCount(int count) {
this.count = count;
}
}
If you do not want to disturb the pojo classes then you can follow below solution to format the json solution and send response.
On JSONObject do below.
obj.put("count", obj.get("total_count"));
obj.remove("total_count");

How do I initialize a final class property in a constructor?

In Java you are allowed to do this:
class A {
private final int x;
public A() {
x = 5;
}
}
In Dart, I tried:
class A {
final int x;
A() {
this.x = 5;
}
}
I get two compilation errors:
The final variable 'x' must be initialized.
and
'x' can't be used as a setter because its final.
Is there a way to set final properties in the constructor in Dart?
You cannot instantiate final fields in the constructor body. There is a special syntax for that:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
// Old syntax
// Point(x, y) :
// x = x,
// y = y,
// distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
// New syntax
Point(this.x, this.y) :
distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point(this.x, this.y)
: distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
If you have some more complicated initialization you should use factory constructor, and the code become:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point._(this.x, this.y, this.distanceFromOrigin);
factory Point(num x, num y) {
num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
return new Point._(x, y, distance);
}
}
Here is a simplified summary of the ways to initialize a final class variable.
class MyClass {
final int x; // <-- initialize this
}
Initializer value
class MyClass {
final int x = 'hello'.length;
}
You'd only use final if the initialization could only be done at runtime. Otherwise, static const is better:
class MyClass {
static const int x = 0;
}
Initializer formal
class MyClass {
MyClass(this.x);
final int x;
}
This is the most common approach.
Initializer list
class MyClass {
MyClass(int x)
: _x = x;
final int _x;
}
This is useful when you want to keep a field private.
Default parameter value
You can surround the parameter with square brackets ([]) for an unnamed parameter or curly braces ({}) for a named parameter and then give it a default value.
class MyClass {
MyClass({this.x = 0});
final int x;
}
This is useful if you want to make the parameter optional.
You could accomplish the same thing with an initializer list as well:
class MyClass {
MyClass({int? x})
: _x = x ?? 0;
final int _x;
}
Late initialization
class MyClass {
MyClass(String? a) {
x = a?.length ?? 0;
}
late final int x;
}
This is useful if you need to do more complex initialization than is allowed in the initializer list. For example, I've done this when initializing a gesture recognizer in Flutter.
Lazy initialization
Another advantage of using late is that it doesn't initialize a value until you access the value.
class MyClass {
late final int x = _doHeavyTask();
int _doHeavyTask() {
var sum = 0;
for (var i = 0; i < 100000000; i++) {
sum += 1;
}
return sum;
}
}
This is useful if you have a heavy calculation that you only want call if you absolutely need it.
This doesn't initialize x:
final myClass = MyClass();
But this does initialize x:
final myClass = MyClass();
final value = myClass.x;
I've had a similar problem: I was trying to initialise a final field from the constructor, while simultaneously calling a super constructor. You could think of the following example
class Point2d {
final int x;
final int y;
Point2d.fromCoordinates(Coordinates coordinates)
: this.x = coordinates.x,
this.y = coordinates.y;
}
class Point3d extends Point2d {
final int z;
Point3d.fromCoordinates(Coordinates coordinates)
:this.z = coordinates.z,
super.fromCoordinates(coordinates);
}
/// Demo class, to simulate constructing an object
/// from another object.
class Coordinates {
final int x;
final int y;
final int z;
}
Well apparently this works. You can initialise your final fields by using the above syntax (check Point3d's constructor) and it works just fine!
Run a small program like this to check:
void main() {
var coordinates = Coordinates(1, 2, 3);
var point3d = Point3d.fromCoordinates(coordinates);
print("x: ${point3d.x}, y: ${point3d.y}, z: ${point3d.z}");
}
It should prin x: 1, y: 2, z: 3
I've come to a dilemma here where I wanted to initialize a final List with no items, and a Stream to be defined inside the constructor (like in this case distanceFromOrigin).
I couldn't do that with any of the answers below, but I mixed them both and it worked.
Example:
class MyBloc {
final BehaviorSubject<List<String>> itemsStream;
final List<String> items = [];
MyBloc() : this.itemsStream = BehaviorSubject<List<String>>.seeded([]) {
items.addAll(List.generate(20, (index) => "Hola! I'm number $index"));
itemsStream.add(items);
}
}
class A{
final int x;
A(this.x){
}
}

How to make the processing of collisions for objects of the same class?

// array containing the active humans.
public final Array<Human> activeHumans = new Array<Human>();
// object pool.
public final Pool<Human> humanPool = new Pool<Human>() {
#Override
protected Human newObject() {
return new Human(100, 500);
}
};
............................................................................
#Override
public void update(float dt) {
checkCollisions();
}
public void checkCollisions() {
// human-human collision
for (int i=0; i<activeHumans.size(); i++) {
Human h1 = activeHumans.get(i);
for (int j=0; j<activeHumans.size(); j++) {
Human h2 = activeHumans.get(j);
if (h1.getRectangle().overlaps(h2.getRectangle())) {
h1.setX(h1.getX() + 2);
}
}
}
}
Somehow, all the objects Human (h1 and h2) make setX(h1.getX() + 2);. How to fix it? I need only one of them stepped aside
Maybe you can change the second loop so to avoid checking an object overlaps with itself (it will always do!) and also avoid checking each pair twice:
for (int j=i+1; j<activeHumans.size(); j++) ...

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}