I've made a class named 'Car'and I have this code.
Car c=new Car(), yourCar;
and I don't know what 'yourCar' means
Is is same asCar myCar = new Car(); Car yourCar = new Car();
?
I can't understand after the comma.
package ex2_datatypecasting02;
class Car{
String name = "car";
String print() {
return name;
}
}
class Bus extends Car{
String name = "bus";
String print() {
return name;
}
}
public class CastingExam {
public static void main(String[] args) {
Car myCar = new Car(),yourCar;
Bus myBus = new Bus(),yourBus;
System.out.println(myCar.print());
System.out.println(myBus.print());
yourCar = myBus;
yourBus = (Bus)yourCar;
System.out.println(yourBus.print());
}
}
You can declare multiple variables of the same type on one line by separating them with a comma (,). Like:
//declare three integers
int x, y, z;
which is equivalent to:
int x; // declare x
int y; // declare y
int z; // declare z
So here I have declared three integers, but I have not initialized them. You can also initialize one or more of them, like:
//declare three integers, initialize two of them
int x = 1, y, z = 4;
// ^ ^ initialized
which is equivalent to:
int x = 1; // declare and initialize x
int y; // declare y
int z = 4; // declare and initialize z
Here we have declared three variables, and initializes x and z with 1 and 4 respectively.
So the statement declares two Car variables: c and yourCar, and c is initialized with a new car, yourCar is not.
As Willem well explained, this statement :
Car myCar = new Car(),yourCar;
is valid and allows to declare two Car variables but initializes only one of them : myCar.
yourCar is indeed null here.
I would like to add that this way of doing spares you a line but is really error prone.
To get a better readability of your code, you should declare each variable on a distinct line :
Car myCar = new Car();
Car yourCar;
It produces the same result but it is much clearer.
Related
If I have a method e.g.
public int addition(int x, int y)
{
int z = x + y
return z;
}
public int usez(int z)
{
// TODO
}
public static void main(String [ ] args)
{
classname d = new classname();
d.usez(z)...
}
z is not readable. So, is there a way to make the resulting z from the first method into the usez method when testing it in main =/
hopefully this makes some sense! in a real version e.g. if x,y = 1,2 then z = 3 I want the main method to recognise z to be 3.
z is a private local variable for the method addition. You can't and should not attempt to access it. However, it's value is returned by the function it's defined in (addition). Therefor, you can do the following:
classname d = new classname();
int zValue = d.addition(1,2);
d.usez(zValue);
Assuming that all methods including main() are in same class, You can make z as class member variable as
int z= 0;
and assign value to it in
public int addition(int x, int y)
{
z = x + y
return z;
}
and use in usez(z).
public static void main(String [ ] args)
{
classname d = new classname();
d.usez(z)...
}
If you are not allowed to initialize a final non-static data member twice, then how can I set x to something that I want in the following example?
class Temp6
{
final int x;
Temp6()
{
System.out.println(this.x);
this.x=10;
}
public static void main(String[]s)
{
Temp6 t1 = new Temp6();
System.out.println(t1.x);
}
}
Java by default gives x a value of 0, so how can I change it to 10?.
A variable marked final in Java can only be initialized once.
Simply declaring x with final int x; does not initialize it. Therefore, it is legal to assign to x in the Temp6 constructor. However, you would not be able to assign a different value to x after the constructor.
That is, the assignment to t1.x in the following:
public static void main(String[] s) {
Temp6 t1 = new Temp6();
t1.x = 11; // ERROR
}
is not legal.
Initialize final variables in the class constructor.
public class Blam
{
private final int qbert;
public Blam(int qbertValue)
{
qbert = qbertValue;
}
}
Reading this.x in your code should give an error, because final variables are not initialized upon declaration. t1.x should be 10 because x is definitely assigned at the end of the sole constructor.
You have to swap the two lines in the constructor for it to compile and it will be 10 there.
class Temp {
int x; // declaration and definition; defaulted to 0
final int y; // declaration, not initialized
Temp() {
System.out.println(x); // prints 0
x = 1;
System.out.println(x); // prints 1
x = 2; // last value, instance.x will give 2
System.out.println(y); // should be a compiler error: The blank final field y may not have been initialized
y = 3; // definite assignment, last and only value, instance.y will be 3 whereever used
System.out.println(y); // prints 3
y = 4; // compile error: The final field y may already have been assigned
}
}
I never thought about this before, interesting point here.
Final field variables behave like local variables in methods, they must be explicitly assigned before usage (definite assignment is hard to formalize, see JLS reference, but it's quite logical).
If you want to give a value to x from outside, you could do it like this:
public class Temp {
private final int x;
public Temp(int x) {
this.x = x;
}
public int getX() { return this.x; }
public static void main(String[] args) {
Temp temp = new Temp(10);
System.out.println(temp.getX()); // 10
}
}
final variable are java constants. They should be initialized before class loads.
final int x=10;
If your final variable is static then it's not like you have to give the value at the declaration itself, you can have something like -
class Demo {
static final int x;
static {
x = 10;
}
}
static block gets executed only once, at the time of class loading
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
import java.util.Scanner;
import java.lang.Math;
public class Assignment1{
//instance variables
double a;
double b;
double c;
// method
public double hypot(double x, double y){
x = x*x;
y = y*y;
double z = x+y;
z = Math.sqrt(z);
return z;
}
// constructor
public Assignment1(double a , double b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public static void main(String [] args){ // execution starts from here
Assignment1 obj = new Assignment1(a,b,c);
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
}
}
What is the problem with this code... I m creating the objects... then it should worl fine !! Aint it???
In your main method (which is static) you are trying to access a b and c fields which are non-static without any reference to Assignment1 instance.
You need to understand that non-static members of class belongs to instance of class and they can be access only via such instance.
In non-static methods like
void someMethod(){
field = 42;
}
you can use field without reference to instance only because compiler will add this. to variable for you which will represent current instance. In static methods there is no this because static methods/fields belong to entire class, not to instances.
To solve your problem consider either first creating "unset" instance of Assignment1 class (lets say you set its values to 0) like
Assignment1 obj = new Assignment1(0, 0, 0);
then you can set its field to data from user like
obj.a = in.nextDouble();
obj.b = in.nextDouble();
and lastly you can calculate c value using
obj.c = obj.hypot(obj.a, obj.b);
BTW direct manipulation of object field is consider bad design. Instead you should create getters and setters (methods like getA() setA(int newA)) which will return or manipulate their values.
a, b and c are instance members. You main method is a class member.
You're trying to mix the two, which won't work.
Also, since you don't really need a custom constructor for your Assignment1 class, you can delete it.
Instead, try something like this:
public static void main(String [] args){ // execution starts from here
Assignment1 obj = new Assignment1();
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
}
Of course its wrong,
you create a instance of Assignment1 with these Codes first:
Assignment1 obj = new Assignment1(a,b,c);
where are a and b and c??
maybe you should use null first:
Assignment1 obj = new Assignment1(null,null,null);
then use the Scanner.in to initialize a ,b and c
You should make a new class for Assignment. Having the main method here is a bit confusing. That said, the problem is that the first line of your main method:
Assignment1 obj = new Assignment1(a,b,c);
Accesses variables a, b, and c, which are non-static variables. This means they do not exist in the context of the static main function.
An alternative way to write this would be:
// Place this in a file called Assignment.java
import java.util.Scanner;
import java.lang.Math;
public class Assignment {
double a;
double b;
double c;
public double hypot(double x, double y) {
x = x*x;
y = y*y;
double z = x+y;
z = Math.sqrt(z);
return z;
}
public Assignment(double a , double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
} // end class Assignment
// Place this in a file called Main.java
public class Main {
public static void main(String [] args){ // execution starts from here
// Give some values to a, b, and c!
double a = 1;
double b = 1;
double c = 1;
Assignment obj = new Assignment(a,b,c);
Scanner in = new Scanner(System.in);
System.out.println("Enter the values to compute the pythagoras theorem");
obj.a = in.nextDouble();
obj.b = in.nextDouble();
obj.c = hypot(a,b);
System.out.println("The hypot is"+ c);
} // end method main
} // end class Main
As a general rule of thumb, try leave your main class empty of everything except the main method. It's even clearer if you call the class that contains the main method public class Main. Hope this helps!
How do I access the method variable having the same name as the inner class member instance or method local variable of the inner class?
class A{
int a = 10; //1
public void someMethodA(){
final int a = 20; //2
class B{
int a = 30; //3
public void someMethodB(){
int a = 40; //4
System.out.println("a = "+a); //access 4
System.out.println("a = "+this.a); //access 3
System.out.println("a = "+A.this.a); //access 1
System.out.println(?????); //how do I access value of a i.e 2
}
}
}
}
No. You can't do that. The reason being, the variable a in position 2 is a local variable, which can only be accessed with it's simple name, in the enclosing scope. From JLS §6.4:
A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).
Now, this clears that you can only access that variable with just a. But, you have another variable in method local class B which shadows that local variable a in position 2, which is again shadowed by local variable in position 4.
Now in print statement, a would access the variable from nearmost enclosing scope, that is local variable at position 4. If you remove that variable, it will print the variable at position 3. And then if you remove it, it will print the variable at position 2.
So, the point is, there is no way to access the local variable a at position 2, because that is shadowed.
that code will never output those statements, here is an example from Sun that should explain things :
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
I am not sure, what you actually mean, but you access a class member with the same name as a local variable with the same name like this:
public class A
{
int a = 10;
public void someMethodA()
{
int a = 5;
this.a = 20; //change the member a from 10 to 20
a = 30; // changes the local variable, which is only known in this method to 30
}
}
Typically this pattern is used in constructors, to name the params the same as member variables, for example:
class Foo
{
private int bar = 10;
private string fooBar = 20;
public Foo(int bar, string fooBar)
{
this.bar = bar;
this.fooBar = fooBar;
}
}
I have written a piece of code :
public class Child{
int y ;
private static final int z = getZ();
static {
System.out.println("The value of z is "+z);
}
public int getX(){
System.out.println("get x");
return 10;
}
public int getY(){
Child ch = new Child();
System.out.println("get y");
ch.y = getX();
return y;
}
public static int getZ(){
System.out.println("get z");
return new Child().getY();
}
public Child(){
System.out.println("Child constructor");
}
public static void main(String...args){
Child ch = new Child();
System.out.println("the value of z in main is "+z);
}
}
And the output is :
get z
Child constructor
Child constructor
get y
get x
The value of z is 0
Child constructor
the value of z in main is 0
Can anyone please explain me why the value of z is 0 and not 10 ?
EDIT:- Thanks everyone , I got the answer to my first question . I still have a doubt , as far as I know the static blocks are executed after the class is loaded and before the first object of the class is instantiated . Well then the SOP("The value of z is "+z) should have been executed before SOP("Child constructor") ! Ain't it ?
Look at getY():
public int getY(){
Child ch = new Child();
System.out.println("get y");
ch.y = getX();
return y;
}
The first three lines are irrelevant - they don't change the value of y in this instance, which is what gets returned.
You're creating an awful lot of pointless objects in frankly spaghetti code, called while initializing the same class that you're constructing instances of. I suggest you try to keep your code a lot simpler than this. Static initializers should be avoided where possible to start with, let alone ones that go all round the houses to do no useful work.
because getY() sets ch.y to 10, but returns the value of this.y.
In GetY you return this.y which never gets set.
On getY() you returned the uninitialized y variable instead of the Child ch instance.
Its because inside getY() method you are constructing a new CHild object and you are assigning 10 to that instance of variable y and when you return y that will be the current instance variable y.
I hope it explains .
To your second point, static fields and static blocks are initialized / executed in textual order.
Eg:
public class StaticTest()
{
static
{
System.out.println("s1 in block 1 :" + s1);
}
private static String s1 = "s1";
static
{
System.out.println("s1 in block 2 : " + s1);
}
public static void main(String args[])
{
new StaticTest();
}
}
The output of this will be -
s1 in block 1 :
s1 in block 2 : s1