Initializing values to constructor using main method - java

How to initialize the values in constructor that the values cannot be passed by object and that we could pass them from main method?
class ex
{
int a,b;
ex()
{
this.a=b;
}
public static void main(String args[])
{
//here we pass the values to that consructor ex
ex obj=new ex();
}
}

make an overloaded constructor which accepts two arguments.
public ex(int a, int b) {
this.a = a;
this.b = b;
}
public static void main(String...args){
ex obj = new ex(1,2)
}
values canntot be passed by object we should pass from main method
If i understand correctly, you want to pass arguments from the main method and nitialize them in your constructor, the only was to do is by passing them to the constuctor while object creation

You can call setter method from constructor if don't want to display initialization values while declaring new object.
Please see code below for reference :
class Testcl {
int a,b;
Testcl(){
setValues(1,2);
}
private void setValues(int a, int b){
this.a=a;
this.b=b;
}
public static void main(String [] args){
Testcl test = new Testcl();
System.out.println("a : " + test.a + " b : " + test.b);
}}

The first thing to say is that this does actually "work" ... in the sense that it compiles and executes without any errors.
int a,b; // default initialized to 'zero'
ex() {
this.a=b; // assigns 'zsro' to a.
}
But of course, it doesn't achieve anything ... because a is already zero at that point.
Now the main method could assign something to the a and/or b fields after the constructor returns. But there is no way (in pure Java1) to get some non-zero value into b before the constructor is called ... if that is what you are asking.
The practical solution is to just to add a and b arguments to the constructor.
1 - a non-pure Java solution might be to "monkey around" with the bytecodes of the constructor so that it does what you "need" to do. But that's pretty horrible, and horrible solutions have a tendency of coming back to bite you.

Related

(Java) Pass a parameter from a constructor to all the methods of a class

Say I have two methods in class 1. Can I pass a parameter to class 1 constructor which would then pass the parameter to both of the methods? Something like the example code below:
class stuff{
int c;
stuff(x){
c = x;
}
public static int sum(int a, int b){
stuff self = new stuff();
return c*(a + b);
}
public static int mult(int a, int b){
return c*(a*b);
}
}
class test{
public static void main(String args[]){
stuff foo = new stuff(5);
System.out.println(stuff.sum(1, 2));
System.out.println(stuff.mult(1, 2));
}
}
So from class test I want to access both methods from class stuff, while passing the parameters for the methods, but I also want to pass a global class parameter (5 in this case). How can I do this?
First two important things :
Constructors are designed to create instances.
Class names should start with an uppercase.
As you write :
class Stuff{
int c;
Stuff(x){
c = x;
}
...
}
Here you assign x to a c field.
But sum() and mult() are static methods.
They cannot use the c field.
Make these methods instances methods and you could use c in these methods.
public static void main(String args[]){
Stuff foo = new Stuff(5);
System.out.println(foo.sum(1, 2));
System.out.println(foo.mult(1, 2));
}
And use the current instance in these instance methods to sum or multiply current value with passed parameter values :
public int sum(int a, int b){
return c*(a + b);
}
public int mult(int a, int b){
return c*(a*b);
}
Just remove 'static' keyword from your methods, and do not create new instance of 'stuff' in a sum method. Instead just create instance of stuff in test#main method like you do right now, and it will work like you wanted.

chain functions

I have two classes
Class1:
public class Class1 {
public static void main(String[] args) {
Class2 classObject = new Class2();
classObject.add(2, 3);
classObject.print();
}
}
And Class2:
public class Class2 {
public int add(int a, int b) {
int n = a + b;
return n;
}
public void print() {
System.out.println(add(2,3));
}
}
I want to use the print method to print out what is being returned in the add method.The add method gets its information from the classObject as seen in Class1.
I know there are different ways to go about doing this, but i'm quite sure that there is a way to do it the way i want to, i just can't figure out how.
In Class2 in the print method when i called the add method i put arbitrary numbers there. What i want to do is somehow bring the numbers from from classObject.add(int,int) and print the the returning integer n.
If what you want to demonstrate is showing an object with state, maybe you mean something like this:
public class Class2 {
int n;
public void add(int a, int b) {
n = a + b;
return n;
}
public void print() {
System.out.println(n);
}
}
This way Object1 never knows the internals of Object2, and it's really a pretty good abstraction.
You can simply change the signature of the print method as below. Method like print are processing methods which needs the input which you can pass as method arguments.
public void print( int a) {
System.out.println(a);
}
Now you need to make a simple call like below.
classObject.print(classObject.add(2,3));
You should not be calling add method from inside the print method. As per the name it seams print is a general purpose method. You should pass input as method arguments and it should be responsible to print the input.
If you wish your print method to just print addition then You can pass the two numbers as input parameters to method print and also change the method name as below. You need to call the method add from inside the print (modified version). In this case you should hide the method add and make it private.
public void printTheAddition(int n, int m){
System.out.println(add(n,m));
}
In this case just call printTheAddition method with two input arguments.

Can a method be called by an object inside of the same class?

What I'm trying to understand is why I'm receiving an error when I try to call a method by an object whilst residing in the same class.
My syntax looks correct. I understand the local variables inside of the method are uninitialized, and wanted to see if the compiler would be able to pick this up.
My issue however is, I receive a stupid error from the compiler, when I try to invoke the method on an object of the same class, within the class, as such.
class Wool {
public static void main (String [] args) {
int add() {
int x;
int a = x + 3;
return a;
}
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
There error that I receive from the compiler is:
c Wool.java
Wool.java:5: ';' expected
int add() {
^
I can do the above fine, if the object of type Wool is instantiated in another class, and the object has no issue in invoking the method, to show me the compilation error that the local variables need a value in that method.
I just don't understand why I can't do it in one class. And if it is possible, please could you educate me.
Help would be immensely grateful.
Thank you.
You can't define a method inside another one. You must declare the add method outside of the main method.
Change your code to
class Wool {
int add() {
int x = 0; // give a value to avoid another error
int a = x + 3;
return a;
}
public static void main (String [] args) {
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
You are declaring a method inside main(). You can not do that.
Methods must be declared inside classes, not inside other methods.
Because add() is not defined as a class method, but you define it as "local" method within main, which is not allowed in java. You must change it to
class Woo{
void add(){
....
}
public static void main(String[] args){
new Woo().add();
...
}
}
You have a method directly inside a method:
main(){
add() {
}
}
that's illegal in java.
Put your method add in the body of your class but not in the body of your method main. Or better : leave Java alone :)
You can't declare a method inside a method.
Try this:
public static void main (String[] arts) {
//
}
int add() {
//
}

Static vs Dynamic Binding Logic

I have the following code:
import java.lang.*;
public class Program
{
public static void main(String [] args)
{
B a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i)
{
System.out.println(i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println(i);
}
}
When I execute this code using B a = new A() , I get 20.0 in both cases which makes sense because overloading is handles during compile time where the compiler looks at the declared type and calls a function appropriately. Since our declared type was class B, class B's method was called in both cases. Now if I do A a = new A(); , I should be getting 10 in both answers but I am not. I am getting 10 for a.p(10) and 20.0 for a.p(10.0). Based on the concept of static binding and whole notion of overloading being done by static binding which looks at the declared type as opposed to the actual type, why is the result coming out this way ? I would very much appreciate your help.
An int can be widened to a double, but not the other way around. This means that 10 can call B.p(double) or A.p(int) but 10.0 is a double and will not be implicitly converted to an int i.e. only B.p(double) will be called.
Its because your method p is not an overridden method, it is just inhereted in your sub-class when you use
Super sup = new Sub();
sup.p(int);
sup.p(double);
In this case as your Super class has a method which takes double as a parameter and aa an int can fit into a double your Super-class's method is invoked the one which accepts double.
Sub sup = new Sub();
sup.p(int);
sup.p(double);
In this case however, as your subclass doesn't have a method which takes a double, for sup.p(double) call it uses the inherited method from super class if you pass double as an argument.
In your case, your are doing overloading which will get binded at compile time(static binding.).And static binding happens with type of reference rather than the type of object the reference is pointing.
In your first case you are using a reference variable of B and assigning an object of A to it.Since your reference is B, the method p(double) from B will get binded statically even if you use an int(since int can be widened to double).
In the second case you are using reference as A itself.In this case, you have two p() methods available.One is p(double) from B and other p(int) from A.So p(10) will call p(int) and p(10.0) will call p(double)
Try this:
class B {
public void p(String i)
{
System.out.println("parent:"+i);
}
}
class A extends B{
public void p(int i)
{
System.out.println(i);
}
}
public class Test1 {
public static void main(String args[]) {
A a = new A(); //arg
a.p(10);
a.p("sample");
}
}
If you change the line marked arg to B a = new A(), you will see compiler trying to call parent p in both the cases.
When you write A a = new A() you create a new object of type A, which will have 2 methods. A.p(int) and B.p(double), and when you call A.p(10.0), it will call B.p(double) due to lack of conversion.
This counter-example might help:
import java.lang.*;
public class X
{
public static void main(String [] args)
{
B c = new A();
c.p(10);
c.p(10.0);
c.p("AAA");
((A)c).p(10);
}
}
class B {
public void p(String s)
{
System.out.println("B: my string is " + s);
}
public void p(double i)
{
System.out.println("B: twice my double is: " + i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println("A: my number is " + i);
}
}
Output:
C:\temp>java X
B: twice my double is: 20.0
B: twice my double is: 20.0
B: my string is AAA
A: my number is 10
The issue is:
1) You're declaring the type as "B" (not "A")
2) B.p(10) can accept an int as a floating point argument
3) Consequently, that's what you're getting
It's really an issue of what argument types can be implicitly converted, than what methods are overloaded or overridden.
When the object has declared type B, the double version is invoked because it's compatible with an int argument, since in Java int is a subtype of double.
When the object is declared as a A, it has the method p() overloaded with two versions:
p(int arg);
p(double arg);
So, when you pass an int, the first version is picked because it's more accurate, and when you pass double the second one, because it's the most specific signature.
For reference, see the relevant JLS at ยง15.12.2 and this post by Gilad Bracha. BTW, don't try to figure out how the language should behave based on what you think is the most logical way, because every programming language is an engineering effort, and this means that there's a price you pay for whatever you take. The primary source of information for Java are the JLS, and if you read it carefully, you'll (surprisingly?) discover that there are even cases where the line in the source code is ambiguous and cannot be compiled.
To make the effect of widening of int to double more vivid I have created another example which is worth looking. Here, instead of double I have created a class called Parent and instead of int a Child class is created.
Thus,
double ~ Parent int~Child
Obviously child object can be widened to Parent reference.
package test;
public class OOPs {
public static void main(String[] args) {
Child ch = new Child(); // like int 10
Parent pa = new Parent();// like double 10.0
B a = new A(); // case 2 : A a = new A();
a.p(ch);// 10
a.p(pa);// 10.0
}
}
class B {
public void p(Parent i) {
System.out.println("print like 20");
System.out.println(i.getClass().getName());
}
}
class A extends B {
public void p(Child i) {
System.out.println("print like 10");
System.out.println(i.getClass().getName());
}
}
class Parent {
String name;
Parent() {
name = "Parent";
}
public String getName() {
return name;
}
}
class Child extends Parent {
String name;
Child() {
name = "Child";
}
public String getName() {
return name;
}
}
Case 1 - Output (B a = new A();)
print like 20
test.Child
print like 20
test.Parent
Case 2 - Output (A a = new A();)
print like 10
test.Child
print like 20
test.Parent

Passing arguments in main method in java class

Can someone tell me what is the need to declare a class like this:
public class Test {
String k;
public Test(String a, String b, String c){
k = a + " " + b + " " + c; //do something
}
public void run(){
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test(l,m,n);
obj.run();
}
}
Of course it works but I don't get the point why would one use such way to implement something. Is it because we need to pass arguments directly to the class main method that is why we use this way or is there some other reason?
What is the purpose of public Test(...) using the same class name. Why is it like this?
The public Test(...) is a constructor and its purpose is for object creation. This is clearly seen from the sample code...
Test obj = new Test(l,m,n);
The variable obj is instantiated with object Test by being assigned to the Test's constructor. In java, every constructor must have the exact same name (and case) as the java file it's written in (In your case constructor Test is found in Test.java).
...Why is it like this?
It all depends on what you want to do with your object. You could have a zero-argument constructor (i.e. requires no parameters) and have methods to set your l, m, n, like so:
package net;
public class Test {
private String k;
/**
*
*/
public Test() {
super();
// TODO Auto-generated constructor stub
}
public void set(String a, String b, String c) {
k = a + " " + b + " " + c; //do something
}
public void run() {
System.out.println(k);
}
public static void main(String[] args) {
String l = args[0];
String m = args[1];
String n = args[2];
Test obj = new Test();
obj.set(l, m, n);
obj.run();
}
}
As you can see, it's exactly the same feature as your example but with a zero-argument constructor.
If your class has no constructor at all, java adds a public zero-argument constructor for you automatically.
Hope this helps.
The method called Test is a so-called constructor for the Test class. The constructor is the method that gets called when you write something like new Test(...).
Bear in mind that the main method is a static method, which means that it does not require an instance of the class Test to be called. This is not the case for the run method. run is an instance method, and to invoke it you need an instance of the Test class (the obj in your case).
The public Test(...) bit is the constructor of that class. It always has the same name as the class. Classes and main methods are two quite different aspects of programming. Classes define reusable components that have both state and methods. The main method is a special method that gets called from the command line.
Your example is so trivial that it doesnt really show any benefits of Object Orientated Programming. If you consider an example where you had different Classes intetracting you might get more of a feel for it.
The main method is the entry point for the program and is called when you run java Test from the command line.
public Test(String a, String b, String c) is a public constructor for the Test class and is called when you call new Test(l,m,n); Note that a in the constructor and l in main method refer to the same String... this also applies to b and m; c and n.
As a side note, this class expects to be passed three values from the command line, and then stores them in l, m, and n
One last note: If you have a method with the signature public void run(), your class should likely implement Runnable so that it can be used in a Thread.
Learn Java.
A constructor is a function that gets called to create an object, and it's denoted by a function with the same name as the class, but no return type. Multiple constructors can be declared with different arguments.
In this case, the arguments are taken out of the argument array and passed as arguments to the constructor for Test.
These are fundamentally basic concepts to the Java programming language. You should read up on Java. Try Thinking in Java, this is a great book to get started.

Categories