Java - Add Parameter to Class - java

I am trying to add a parameter at the declaration of a class.
Here is the declaration:
public static class TCP_Ping implements Runnable {
public void run() {
}
}
This is what I am trying to do:
public static class TCP_Ping(int a, String b) implements Runnable {
public void run() {
}
}
(which doesn't work)
Any suggestions? thanks!

You probably want to declare fields, and get the values of the parameters in the constructor, and save the parameters to the fields:
public static class TCP_Ping implements Runnable {
// these are the fields:
private final int a;
private final String b;
// this is the constructor, that takes parameters
public TCP_Ping(final int a, final String b) {
// here you save the parameters to the fields
this.a = a;
this.b = b;
}
// and here (or in any other method you create) you can use the fields:
#Override public void run() {
System.out.println("a: " + a);
System.out.println("b: " + b);
}
}
Then you can create an instance of your class like this:
TCP_Ping ping = new TCP_Ping(5, "www.google.com");

Use Scala! This is supported nicely.
class TCP_Ping(a: Int, b: String) extends Runnable {
...

You cannot declare concrete parameters on the class heading (there are such things as type parameters, but that's not what you need as it appears). You should declare your parameters in the class constructor then:
private int a;
private String b;
public TCP_Ping(int a, String b) {
this.a = a;
this.b = b;
}

Related

How can I have a Java class where an instance variable may be of different types?

I have a class defined like:
public class Test {
private String a;
private String b;
public Test(String a, String b) {
super();
this.a = a;
this.b = b;
}
}
At some point I create instances of this class and put them in a List<Test> ArrayList. The problem is sometimes I want a to be of type double not String (i.e. Use another constructor in which a is a double). I'm also interested in always storing the value in a variable called a no matter what. This means creating another instance variable of type double with a different name will not do. It would not be a problem to just make a new class with an instance variable a of type double if it wasn't for the fact that the two classes would not be able to go into the same ArrayList which is also something I need done.
One thing I've seen that could help is to make a List<Object> ArrayList which can hold instances of any class, but I think this is considered bad practice. Any ideas on how I could achieve what I'm trying to do?
While you could do something with generics, that's probably not what you want. There is no bound on the type parameter T, so its type is effectively Object. All you can do is print its value and test for equality, you can't use it in an arithmetic expression (if it's a Double).
public class Test<T> {
private T a;
public Test(T a) {
super();
this.a = a;
}
public void doSomething() {
a.??? // only methods on Object can be called here
}
public static void main(String... args) {
List<Test<?>> tests = new ArrayList<>();
tests.add(new Test<String>("foo"));
tests.add(new Test<Double>(42.0));
}
}
You are probably better off with a type hierarchy, but it depends on what you are actually doing:
public interface Test {
boolean doSomething();
class TestString implements Test {
private final String a;
public TestString(String a) {
this.a = a;
}
#Override
public boolean doSomething() {
return a.contains("foo");
}
}
class TestDouble implements Test {
private final double a;
public TestDouble(double a) {
this.a = a;
}
#Override
public boolean doSomething() {
return a > 10.0;
}
}
static void main(String... args) {
List<Test> tests = new ArrayList<>();
tests.add(new TestString("foo"));
tests.add(new TestDouble(42.0));
}
}

Static and non-static method in one class with the same name JAVA

I know it is impossible to override a method in one class. But is there a way to use a non-static method as static? For example I have a method which is adding numbers. I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?
EDIT:
What I mean is, if I make a method static I will need it to take arguments, and if I create an object with variables already set it will be very uncomfortable to call function on my object with same arguments again.
public class Test {
private int a;
private int b;
private int c;
public Test(int a,int b,int c)
{
this.a = a;
this.b = b;
this.c = c;
}
public static String count(int a1,int b1, int c1)
{
String solution;
solution = Integer.toString(a1+b1+c1);
return solution;
}
public static void main(String[] args) {
System.out.println(Test.count(1,2,3));
Test t1 = new Test(1,2,3);
t1.count();
}
}
I know the code is incorrect but i wanted to show what I want to do.
I want this method to be usefull with an object and also without it.
Is it possible to do something like that without creating another
method?
You will have to create another method, but you can make the non-static method call the static method, so that you do not duplicate the code and if you want to change the logic in the future you only need to do it in one place.
public class Test {
private int a;
private int b;
private int c;
public Test(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public String count() {
return count(a, b, c);
}
public static String count(int a1, int b1, int c1) {
String solution;
solution = Integer.toString(a1 + b1 + c1);
return solution;
}
public static void main(String[] args) {
System.out.println(Test.count(1, 2, 3));
Test t1 = new Test(1, 2, 3);
System.out.println(t1.count());
}
}
But is there a way to use a non-static method as static?
No, it's not possible.
If you need this method to be used in static and non-static context, then make it static. The opposite configuration, however, is not possible.
Make it static, then it can be used with object and without it.
public class MyTest() {
public static int add() {
System.out.println("hello");
}
}
MyTest.add(); //prints hello
MyTest myobject = new MyTest();
myobject.add(); //prints hello

How java casting work, is it change the state of Object or create new Object?

I have a method dummy with A as class parameter, but i need to pass instance of subclasses B to that method. I know from:
Does Java casting introduce overhead? Why?
that downcasting in java have overhead. Most of my code deal with subclass B so i dont use downcasting for this purpose. Instead i use temporal instance variable cc for that purpose. But this is not make a change for object of subclass m. I need change in variable cc avaliable too for instance variable m. This is my code:
public class TestCast {
public TestCast() {
B m = new B(12, 3);
dummy(m);
A cc = m;
dummy(cc);
System.out.println(m.a);
System.out.println(cc.a);
}
public void dummy(A t) {
t.a = 22222;
}
public static void main(String[] args) {
new TestCast();
}
}
class A {
public int a = 0;
public A(int a) {
this.a = a;
}
}
class B extends A {
public int a;
public int b;
public B(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
}
with output
12
22222
In your particular example, both the parent and child classes declared a field with name a. In this case, the child variable hides the parent variable.
Also, variables/fields are not polymorphic entities like methods. They are accessed by the static type of a reference.
In other words, the field access
A var = new A(10);
var.a; // returns 10
And the field access
A var = new B(1501, 10);
var.a; // also returns 10
but
A var = new B(1501, 10);
var.a; // returns 10
((B)var).a; // returns 1501
because you access a on a reference with static type B.
In your method
public void dummy(A t) {
t.a = 22222;
}
The static type of t is A so you will modify the value of the parent class variable.
Casting is telling the compiler that a reference variable is of specific Type at runtime
Because B is extending A you do not want to re-define the variable a
In answer to your comment, you code should be something like:
class B extends A {
public int b;
public B(int a, int b) {
super(a);
this.b = b;
}
}
IMO, your example code is not perfect implementation of inheritance. Inheritance enables you re-usability of code. In other words, you don't need to declare int a again in class B.
I need change in variable cc avaliable too for instance variable m:
However, if you want to change in variable cc as well, then declare variables a, b as private/protected in both A and B. And provide setters and getters in both classes.
And in class B call super.setA(a) like below.
class B extends A {
private int a;
private int b;
public B(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
public setA(int a) {
super.setA(a);
this.a = a;
}
}

Set and get a static variable from two different classes in Java

Lets say I have 3 Classes: A, Data, and B
I pass a variable from class A which sets that passed variable to a private variable in class Data.
Then in class B, I want to call that specific variable which has been changed.
So I do
Data data = new Data();
data.getVariable();
It will then return null, since in class Data I initialize variables to nothing (ex: int v;), and I think that class B is initializing a brand new class and resetting the values to default, but I don't know how to fix this.
I know that the variable is setting properly because in class A if I do data.getVariable() it will print the variable that was set.
Class A:
Data data = new Data();
int d = 1;
data.setVariable(d);
Class Data:
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
Class B:
Data data = new Data();
private int v;
v = data.getVariable();
System.out.println(v);
This will print out 0 instead of the actual value
When you instantiate a Data object in class A, and instantiate another Data object in class B, they are two different instances of the Data class. They both instantiate d to 0 by default. You then call setVariable on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call setVariable on the instance in class B.
What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the static keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. MyClass.doMethod()). For example:
Class Data (updated):
private static int b;
public static void setVariable(int s)
{
b = s;
}
public static int getVariable()
{
return b;
}
Class A:
Data.setVariable(d);
Class B:
v = Data.getVariable();
System.out.println(v);
Editing - my first suggestion was to use static for variable b, and the author changed his question adding that suggestion.
It fixes what you are trying to do. I write the example in code that compiles:
public class Demo {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.doWhatever();
b.doSomethingElse();
}
}
class Data {
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
}
class A {
public void doWhatever() {
Data data = new Data();
int d = 1;
data.setVariable(d);
}
}
class B {
Data data = new Data();
private int v;
public void doSomethingElse() {
v = data.getVariable();
System.out.println(v);
}
}

Out of order chained constructors

public class ParentClass
{
public ParentClass(int param);
}
public class MyClass extends ParentClass
{
private int _a;
private int _b;
private int _c;
public MyClass(String input)
{
_a=CalculateA(input);
_b=CalculateB(_a);
_c=CalculateC(_a);
super(_b+_c);
}
//a expensive procedure
private int CalculateA(String text);
private int CalculateB(int a);
private int CalculateC(int a);
}
Java doesn't allow chained constructors to be anything other than the first method put in a constructor.
Chained constructors can't call nonstatic methods as arguments (which removes the possibility of using Initialsers that return the value they initialize to).
How do I achieve the above code using legal Java?
Edit Indeed Java does not allow a constructor to do any calculations before the call to a parent's class constructor, even if these involve only static methods (as your calculateX's should be) and results only assigned to variables that are private to the class (like your _a, _b and _c) or local to the constructor.
There is a way around this, however: call another constructor with the result of the calculateX call assigned to its parameter - then you can access this result throughout the other constructor.
public class MyClass extends ParentClass {
private int _a,_b,_c;
public MyClass(String input) {
this(calculateA(input));
}
private MyClass(int a) {
this(a, calculateB(a), calculateC(a));
}
private MyClass(int a, int b, int c) {
super(b + c);
this._a = a;
this._b = b;
this._c = c;
}
private static int calculateA(String text) {
try {Thread.sleep(1000);} catch (Exception e) {} // expensive ;-)
return text.length();
}
private static int calculateB(int a) { /* ... */ }
private static int calculateC(int a) { /* ... */ }
}
Edit 2 With more calculations or more intermediate results to store for later use, this approach would lead to an even longer chain of constructors consisting only of this(...)-calls. A more fancy solution with only two constructors, the public one and one private, is possible with a helper class (reasonably an inner class):
public MyClass(String input) {
this(new InitCalcResult(input));
}
private MyClass(InitCalcResult initCalcResult) {
super(initCalcResult.initB + initCalcResult.initC);
this._a = initCalcResult.initA;
this._b = initCalcResult.initB;
this._c = initCalcResult.initC;
}
private static class InitCalcResult {
private int initA, initB, initC;
InitCalcResult(String input) {
initA = calculateA(input);
initB = calculateB(initA);
initC = calculateC(initA);
}
}
(using the same private fields and static calculateX methods as above).
You can do something like this.
public abstract class ParentClass
{
public ParentClass(String input){
int a = getData(input);
/* Do what ever u need to do with a*/
};
public abstract int getData(String input);
}
public class MyClass extends ParentClass
{
private int _a;
private int _b;
private int _c;
public MyClass(String input)
{
super(input);
}
public int getData(String input){
_a=CalculateA(input);
_b=CalculateB(_a);
_c=CalculateC(_a);
return _b+_c;
}
//a expensive procedure
private int CalculateA(String text){/* return int */};
private int CalculateB(int a){/* return int */};
private int CalculateC(int a){/* return int */};
}
Since getData is abstract, the base class function will get called. And the super class will get the required data.

Categories