I have a question related to OOP.
what is the effect, if we make an object outside the method.
Is that object becomes global?
Here is some code..
class A(){
String b;
public void c(){
//some code in here}
}
class C(){
A a = new A(); //is this ok and if it is ok what is this mean??
public void p(){
a.c(); //Is this possible??
}
}
It seems like you are very new to Java or Object Oriented Programming.
There are two steps to create an object in Java: Declaration and initialization
Declaration means you are declaring that something exists.
Eg: String title; means, there exists a string object named title.
Initialization is assigning value to it. ie: title = "Hello World!";. But before initializing an object you need to make sure it is declared. Also you can combine declaration and initialization in one statement: String title = "Hello World!";
The scope of the object depends up on where you declare that object.
If you declare it inside a class like this:
class Car {
String name; //These are called fields
static String author = "Farseen"
public void doSomething() {..../*can access name and author*/}
public static void doSomething() {..../*can access author only*/}
}
everything inside the class will have access to it, except the static (we'll get to that in a while) methods.These are called fields
If you decalare it inside a method, only that method will have access to it:
class Car {
public void doSomething() {
String name = "BMW"; //These are called local variables
}
public void doSomeOtherThing() {
//Cannot acccess name
}
}
These are called local variables
If you declare it outside a class, sorry Java does not allow you to do that. Everything must be inside a class.
You can prefix declarations outside methods, that are fields with access modifiers:
public : Makes the field accessible to anyone. It is legal to :
Car myCar = new Car();System.out.println(myCar.name);
private : Makes the field accessible to the methods(functions) inside the class only. It is illegal to :
Car myCar = new Car();System.out.println(myCar.name);
protected : Makes the field accessible to the subclasses of that class. It is also not accessible to users, like private.
Now comes in the static modifier:
It says that the field or method(function) belongs to the entire species of car, instead of individual cars.
It is legal to access the static field author like this: Car.author no need to create an individual car, although it is legal : new Car().author
The static things only know about static things, not individual things.
There is no concept of Global Variables in Java. Although, you can achieve it using some thing like this:
class Globals {
public static String GLOBAL_VARIABLE_MESSAGE = "Hello World!";
}
And use it somewhere in your code using Globals.GLOBAL_VARIABLE_MESSAGE
Hope it helps!
Edit: referring to the code added to the question
class A{ //Parenthesis are NOT needed
// or allowed in class definition:
// 'class A()' is wrong
String b;
public void c(){
//some code in here
}
}
class C{ //Same here. No parenthesis needed
A a = new A(); //Q: Is this ok and if it is ok what is this mean??
//A: Yes, completely ok.
// This means you added
// a field 'a' of type A to the class C
public void p(){
a.c(); //Q: Is this possible??
//A: Of course
}
}
I made some edits to your code and added answers to your doubts
class A{
String b;
public void c(){
//some code in here}
}
class C{
A a = new A(); //is this ok and if it is ok what is this mean??--It is Ok.it means that a is instance variable of type A.
public void p(){
a.c(); //Is this possible?? -- It is possible. since c() is a method in class A.
}
}
Where you create an object has little to do with it being "global". It is all about the scope of accessibily of a reference to that object. To give two extreme opposites, both involving instantiation outside of a method:
public static final File f = new File(new File("/x/a"), "b");
The above line will cause two instances of File to be created: one will become global, the other will be completely inaccessible and disposed of on the spot.
Related
My code is like this:
public class HelloWorld{
{
System.out.println("field init " + this.getName());
}
private String name = null;
private InnerClass inner = new InnerClass(this);
private String getName() {
return name;
}
public HelloWorld() {
name = "hello world";
System.out.println("class init");
}
private class InnerClass {
public InnerClass(HelloWorld hello) {
System.out.println((hello == null));
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println("Hello World.");
}
}
As far as I know, field initialization is before constructor, so why "this.getName()" can be called and "this == null" is false?
There'd be little point to calling an instance initializer block if the instance hadn't been created yet, as the purpose of an instance initializer block is to initialize (set the initial information for) the instance (this).
So the JVM creates the instance with all fields set to the "all bits off" default, sets this to refer to that instance, then does any instance initialization you've specified.
More in JLS§12.5: Creation of New Class Instances and JVMS§4.10.2.4.
Side note:
As far as I know, field initialization is before constructor
In effect, yes; the Java compiler prepends instance initialization code to the beginning of every constructor you specify.
Remember that all classes in Java have java.lang.Object as their (ultimate) base class. Before you get to any field initialisation or construction in your class, the this pointer for that base class has already been set up.
Hence, it can never be null.
I came across a code which my colleague uses inside an eventListner, which is :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
new className().methodName(); //public class and public void methodName()
}
I was pretty sure that :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
className ref = new className(); //public class and public void
ref.methodName();
}
is the better option than his, as the previous method instantiates a class every time it is called.
Am I wrong? Any suggestion is appreciated, Please correct me if I am wrong
.
Both do the same thing, however one of them (the first) is 1 line shorter.
Your approach is usually recommended when you need to go through more than 2-3 objects, so new Foo().getBar1().getBar2().doStuff() is usually not recommended since it can degrade into spaghetti code and hinder the understandability of the code.
The first code-sample instantiates a new Object of Type className.methodName.
For this to work, methodName has to be a static nested class of Type className.
Attention: This could as well be a typo. Did you mean new className().methodName()?
The second sample creates a new instance of className and calls its method methodName.
Some example code:
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public String test() {
return "Test";
}
public static class test {
}
}
In order to judge what's the best solution your example does not give enought information. Is the method some static utility code or is an instance of className useful? It depends...
Whenever an object is instantiated but is not assigned a reference variable, it is called anonymous object instantiation.
With anonymous object you can call it's instance method also:
new className().methodName();
In your case this is the anonymous object which doesn't have reference variable.
In the statements:
className ref = new className();
ref.methodName();
ref is the reference variable to hold the className object, so you can call instance methods of className on ref variable.
The benefit of using anonymous notation is, if you want to do only limited (may be calling single method and so on..) operation with the underlying object the it is a good approach. But if you needs to perform more operation with the underlying object then you need to keep that object in a reference variable so that you can use that reference to perform multiple operations with that object.
Regarding the performance there are not much difference as both are in methods scope, as soon as method completes both the objects are valid candidates for the garbage collection.
Both the methods instantiates a class in the code. If you want to reuse the class object every time the method is called, you can declare it as a member of the class where the method resides. For eg:
class AnotherClass{
private ClassName ref;
AnotherClass(){
ref = new ClassName()
}
private void someActionPerformed(java.awt.event.ActionEvent evt) {
ref.methodName();
}
}
This way, everytime your method someActionPerformed is called on an object of AnotherClass, it will reuse the ref object instead of instantiating it everytime.
About the edit,
public class ClassName {
static class InnerClass{
// A static inner class
}
public void methodName() {
// A method
}
}
class AnotherClass{
private void someActionPerformed(java.awt.event.ActionEvent evt){
// This creates an instance of the inner class `InnerClass`
new ClassName.InnerClass();
// However I believe, you wanted to do:
new ClassName().methodName();
}
}
new className.methodName(); --> if you are using this convention in your code then calling another method name will result to different object's method name and you lose your values.
className ref = new className();
ref.methodName(); -> here you are creating a reference and make assiging a newly created object and you are calling the method's on it. Suppose if you want to call another method on the same object it will helps.
The first approach they will mostly use for listenere which is anonymous class.
Both options create a new Class every time they are called. The advantage of the second over the first option would be if you wanted to reuse that class later in the method.
IMHO this is a little bit more understandable code for the answer provided by DaniEll
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public void test() {
System.out.println("Outer class");
}
public static class test {
public test() {
System.out.println("Inner class");
}
}
}
I have a question concerning the use of objects...
I have a class called Area which contains a few methods. I want to access these methods in another class in which an Area object is created.
public class calcAreaObj {
Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Why is it when the class is created as above I get an error("Cannot make a static reference to non-static field areaObj. But when the source code is written such that the Area object is initiaized inside the main statement as below there are no errors...
public class calcAreaObj {
public static void main(String[] args){
Area areaObj = new Area();
areaObj.area(2,3,4);
}
}
Is this because in the first case the Area object is initialized outside of a static statement? If so, why does this matter?
This is because when defined at class scope, areaObj is specific to each instance of calcAreaObj. That's not really what you want, since main is a static method (and so doesn't have an instance of calcAreaObj associated with it). You can either use the second code sample you posted, or you can modify the first one as follows:
public class calcAreaObj {
static Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Additionally, if areaObj doesn't have any state, in this case, you could always declare Area.area as static.
In the first example areaObj is a non-static member of calcAreaObj. This means it can only be accessed using an instance of calcAreaObj.
new calcAreaObj().areaObj.whatever(); //this will work
calcAreaObj.areaObj; //areaObj isn't a static member, won't work
In short: the non-static member doesn't even exist as long as you haven't created an instance of calcAreaObj. In the second example, it's in scope of the method and thus accessible.
For the first situation your creating a local variable for the class which has no relation with the object used in the main. Therefore you have to initialize the object again in the main.
There is a rule: that any block has it's own variables. So if you initialize a variable in block and try to use it outside the block that will give you an error.
For example:
public static void main(String [] arg){
{ Area a = new Area(); }
double number = a.area
}
this doesn't work ...
I wish it is clear
I know that this(...) is used to call one constructor of a class from another constructor. But can we use new for the same?
To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null not Hello?
class Test0 {
String name;
public Test0(String str) {
this.name= str;
}
public Test0() {
//this("Hello"); // Line-1
new Test0("Hello"){}; // Line-2
}
String getName(){
return name;
}
}
public class Test{
public static void main(String ags[]){
Test0 t = new Test0();
System.out.println(t.getName());
}
}
It is valid but it's creating a completely separate instance of Test0 (more specifically an instance of an anonymous subclass of Test0) inside that constructor, and it's not being used anywhere. The current instance still has the field name set to null.
public Test0() {
// this creates a different instance in addition to the current instance
new Test0("Hello"){};
}
Note that if you call the new operator with the no-argument constructor, you would get a StackOverflowError.
What you're trying to do is accomplished by the code you commented out:
public Test0()
{
this("Hello");
}
Line 2 is valid statement. That is why compiler didn't show up any errors. But there you are creating an anonymous object. It will vanish soon after you exit from the constructor. Therefore the value is still null becuase nothing was assigned to that.
new Test0("Hello"){};
Above line will create an anonymous instance of Test0 class and assigned the value of Hello to the name variable. But since you are not referring the created anonymous instance, it will get disappear from the immediate after line. So still you haven't assigned a value to the name variable of the instance that calls the particular code segment. Therefore name is null
In the memory it is like
Because you create a new instance of Test0 with name "hello" but never use it.
public Test() {
new Test0("hello") // nothing is referencing this new object
}
You simply creating an object inside another constructor but it will have no effect on the instance being created by the first constructor call.
You can do this but the result of this new usage will be gone at the end of the constructor. Especially, t.name will be null.
Use this("Hello").
Name is the instance variable. Instance variables are object-specific.
With new Test0("Hello"); you are creating a new instance of Test0.
If you would like to have t.getName() return "Hello" [I mean field value independent of object], change the name field to static:
static String name;
You can display output by using new keyword through below code..Since u have used public Test0(){new Test("Hello){};" here {} braces are not important..so when test0() constructor is called...Inside this constructor test0(args); is being called bt in first constructor u didnot displayed output..where will be your "Hello" will get displayed..so just edit
`
public test0(String str)
{
this.name=str;
System.out.println(str);
}`
And you will have ur desired output..See my below code..
class test01{
public test01(String str)
{System.out.println(str);
}
public test01(){
new test01("Print");
}
}public class Const {
public static void main(String args[])
{test01 t = new test01();
//System.out.println(t.getName());
}}
The output of this code will give u required String
I tried to access a variable in the main class from another class. I don't know if it's possible but I need those variables. If there is a way please show me. This is the simple example.
public class A(){
public static String status;
public static void main(String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Deadlock or no deadlock (y/n)");
status = s.nextline();
......
}
Then I want to use this variable "status" in another class which implements a runnable (thread). If status is "y" then a particular block of codes (if/else) inside the run methon will executes.
Anyone point me how do I call the main class so I can access the variable status from my the runner class. Thanks.
The field status in class A is public and static, so you can call it from wherever you like.
public class B {
public void myMethod() {
System.out.println("A's status is " + A.status);
}
}
A point on terminology: A here is a class, which represents an object. main happens to be a method within that class A. So you'd say that status belongs to A, not to main.
No java is pass by value not pass by reference. You could follow the example I'm linking and see if that helps though.link You could make it static and it would be usable that way but any operations on it would change when ever you perform any on it hence static.