What is the exact meaning of instantiate in JAVA - java

I'am a newbie in JAVA and this came across this word called.
"A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method".
The word in bold.
Can anyone please help me out with this one.I know it's embarrassing and i should've researched more but I just cannot understand.
Thanks.

First of all Declaring mean:
ClassName obj;
Simple meaning of instantiate is creating an object from class.
ClassName obj = new ClassName();
What is a object?
An instance of a class. From one class we can create many instances.
They are the basic runtime entities in in our program.
They may also represent user-defined data types such as lists and
vectors.
Any programming problem is analyzed in terms of objects and nature of
communication between them.
As a example:
//Define a reference(a variable) which can hold a `Person` obect.
Person p;
//Create a Person object(instantiate).
//new - use to allocate memory space for the new object
p = new Person();
What is a nested class?
A class that defined inside a class is called nested class. There 2 categories of nested classes.
inner classes
local classes
annonymous classes
Inner class:
Inner class can only be accessed by the outer class. Not by any other
class.
Inner class is a member of outer class.
Outer class can access inner class without importing.
Inner class can access any attribute or a method belong to outer
directly.
Outer class cannot access directly to a inner class.
Example for a inner class:
class Outer{
int i = 10;
void main(){
//instantiate inner class.
Inner in = new Inner();
in.show();
}
class Inner{
void show(){
System.out.print(i);
}
}
}
What is a local class?
Which are classes that are defined in a block.
Example:
public class{
int i = 10;
public main(){
class A{
void show(){
System.out.println(i);
}
}
//inside the method instantiate local class.
A obj = new obj();
obj.show();
}
//outside the main() -block(method)
//inside another method instantiate local class.
public test(){
A obj = new A();
obj.show();
}
}

To instantiate a class means to create an instance of the class. In other words, if you have a class like this:
public class Dog {
public void bark() {
System.out.println("woof");
}
}
You would instantiate it like this:
Dog myDog = new Dog();
Instantiating is when you use the new keyword to actually create an object of your class.

Instantiate == create an instance == create an object of a class.

Instantiate is creating an instance of a class. I reckon this is not helpful without knowing what an instance is.
Let's say you have a class definition like:
public class Person
{
private String name;
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
You make an instance of this class my calling its constructor and using the keyword new:
Person p = new Person("Hugh Laurie");
An instance of a class is a place in memory that contains the state (e.g., Person::name) of a given object which used as a template a class definition.
I want to further expand upon:
If you want to invoke the methods of local inner class you must instantiate this class
What this means is that, you need to have instantiated that class in order to use the above's example getName() method. After all, it is trying to access the state (name) of a given object in memory; without that object, there is no state.

Instantiate in Java means to call a constructor of a Class which creates an an instance or object, of the type of that Class. Instantiation allocates the initial memory for the object and returns a reference. An instance is required by non-static methods as they may operate on the non-static fields created by the constructor.
Static methods don't need an instance and should not be stateful, i.e. should not rely on changing data. They are essentially free functions that are associated with the type and not a particular instance. When you want to work with changing data, encapsulating that data as member fields that are operated on by instance methods is the way to go.
For example, a Car class might have static numbeOfWheels() that always returns 4, but an instance numberOfFlatTires() that might return 0-4 depending on the state of that particular Car.
Inner classes are no different and the only difference between a static and non-static inner class is that the non-static can use the parent instance's members. This can be used to reduce complexity. You might have a looping operation that has a common parameter for the list and an individual parameter for the items. You could use a non-static inner class to encapsulate the operations on the item while referring to the common parameter in the parent class.
Enums are special in that each value is a single instance of a single type that all extend from a common abstract base class defined in the Enum class body. The Enum value is instantiated the first time it's used, but there will only ever be one instance per value.

when you create an instance of a class or simply called as an object
for ex: Bike abc = new Bike();
as soon as you create this object using the new keyword, a new block of memory is created and object "abc" will now be pointing to that new block of memory, this is called as instantiation in java.

create an instance of the class by using "new" word
for example Car car = new Car();

Related

Is there a way to get all Memberclasses of a class and loop over them to excecute methods?

I have an ManagerCLass, which includes many other Objects. Here are methodes, that takes thes Objects and call an method on theses Objects..
Example:
public class Manager extends BaseManager {
ClassA classA = new ClassA();
ClassB classB = new ClassB();
ClassC classC = new ClassC();
ClassD classD = new ClassD();
ClassE classE = new ClassE();
public void callMethodsOnObjects() {
classA.printResult();
classB.printResult();
classC.printResult();
classD.printResult();
classE.printResult();
}
}
These classes have all the same Superclass. Now my Question is, is there a way to automate the callMethodsOnObjects()-method?
My Idea was to get all declaredClasses of the Managerclass. Then to Loop of the array an excecute the printResult()-methode on each Object.
Class<?>[] classes = Manager.class.getDeclaredClasses();
for (int i = 0; i < classes.length; i++) {
....
}
But this donĀ“t work. The Array is Empty.
So do you have an Idea if this a way to automate this?
There are still more methods that are structured this way.
I'm not getting anywhere here. Does it make sense to do it this way, as I imagined it?
OK, so the real problem here is that you are using Java terminology incorrectly.
There are no member classes of the Manager class. Yup. That's what I said!
A "member class" is a class that is declared inside another class. But there aren't any classes declared inside Manager.
However, there are fields ("member fields") declared inside Manager; i.e. classA, classB and so on. And these fields have classes; i.e. ClassA, ClassB and so on.
If you want to find the member fields of a class, use the Class.getDeclaredFields() method. This will give you an array of Field objects.
You can then get each field's class by calling Field.getType() on it. Then you can use reflection to lookup the classses printResult() method and invoke it on the value in the respective fields of a target object.
Notes:
The Class returned by getType() could denote a primitive type or array type rather than a class. This Class will represent the erased type of the field.
If you want the Type as it was declared in the source code, use Field.getGenericType() instead.

Variable with default access keyword is unable to be accessed in same package's different class

When I access a default (with no access modifier like public or private in front of it) access variable like String s = "hello" from a class A in package com.access.test to class B in same package, I can't obtain the variable s in class B.
IDE shows that variable s is never defined.
But then why does Java say that default access variables can be accessed in the same package. Just like we know that a protected variable can be accessed from different package by extending the class.
So a default variable should be accesses without even making its class A's object instantiation(A a = new A() and then a.s).
Please explain.
You should be able to access it in B via instance of A.
So do it like:
A a = new A();
//print a.s
If you define String a as static then you could access it by class name in B like:
//print A.s
Accessing Class A's Variable directly outside the class even though within the same package is not possible.
Think about it in a simple way, Class B is in the same package but not inheriting class A, right!
So String s; is not a part of class B. Then how can it be accessed directly. You have to create an object of class A in class B and then String s will be accessible.
Just go for the basics of Access Modifiers in Java and you'll come to know that even public variables of a class cannot be accessed outside the class, without its object.
for example:
class Test5
{
public int x=10;
}
class TestMain
{
public static void main(String[] arg)
{
//System.out.println(x); //Generates Compile Time Error
Test5 obj= new Test5();
System.out.println(obj.x);
}
}
In this example, x is public but still not accessible without object of class Test5 even though both the classes are in the same program file.
Same is the case with default modifier also.
Hope this helps.
Consider the following two classes
public ClassA {
String myA = "A string";
}
and
public ClassB {
String myB = "B string";
}
I think you may be confusing accessibility and namespace. Each class definition creates its own namespace. This enables you to create identically named instance fields in separate classes that are still separately encapsulated within each class.
If you wish to access an instance field that has default access in the same package but in a separate class, you must qualify that field name with a class instance (so that the compiler will know where to locate the field; if you do not quality the field name then it is assumed you are only wishing to consider field names in the current scope). For example, to access myA from ClassB you would write:
a = new ClassA();
System.out.println("myA = " + a.myA);

Confusion with subclasses and superclasses

Master test = new Inner();
System.out.println(test.getClass());
In the above example the Inner class extends the Master class, but what I'm confused about is that test.getClass() returns Inner, but isn't test really of the type Master? Other than the constructor no methods/properties can be used from the Inner class, only what's in the Master class. Furthermore the constructor for Inner actually sets properties exclusive to Inner, but somehow these properties don't exist in test even though it uses the constructor -- which doesn't seem like it should work.
For example if define the classes as:
public class Master {
public int number = 0;
public Master() {
number = 9;
}
}
public class Inner extends Master {
public int innerNumber = 0;
public Inner() {
number = 1;
innerNumber = 2;
}
}
test will use Inner's constructor which sets innerNumber, but test.innerNumber doesn't even exist because innerNumber isn't apart of the Master type. Also, test.getClass() says it's of the Inner type, not Master.
Object.getClass() returns the class object of the dynamic type of the object, not the static type (the type of the variable or attribute you declared it).
Hence new Inner().getClass() returns Inner.class, new Master().getClass() returns Master.class no matter what the type of the variable is that holds the reference.
Question 1:
Master test = new Inner();
The above line indicates that get method implementation's from Inner class (ovveriding). So Inner classes getClass() method calls.
Question 2:
test.innerNumber
Inheritance happens from Parent to Child. innerNumber is a property of Inner(child). Master(Parent) won't get it.

Referencing static object created in one class throughout entire application

I have a java application that creates two static objects in a base class, these objects needs to references throughout classes in the program.
public class Baseclass{
public static ClassA A = new ClassA();
public static ClassB B = new Classb();
...
...
...
}
These objects are referenced in the other classes as a local private variables.
public class ClassA{
private ClassB b = Baseclass.B;
However, both object require each other to function and if I creates a new instance of one of the objects before the other is created, the local variable in the "upper" classes is set to null. Is there any concepts in Java that would reference the actual object (like a pointer) to the object as a variable instead of making a copy of the object?
However, both object require each other to function and if I creates a new instance of one of the objects before the other is created, the local variable in the "upper" classes is set to null.
I think the answer you are looking for is a "singleton pattern". This is where you create just one instance of a class for use in other places. Here's a good link to read. Here's the wikipedia page on it with some java examples.
So your code would look something like this:
public class A {
private final static A instance = new A();
/* private constructor forces you to use the getInstance() method below */
private A() {}
public static A getInstance() {
return instance;
}
}
Then wherever you want to get an instance of A you would do something like:
public class B {
private final A classA = ClassA.getInstance();
...
}
There is no reason why A could not also have an instance of B and call B's methods in its own methods. What you cannot do with this cross dependency is call any of the other's methods in the constructor.
In general, by the way, these patterns should be used sparingly. A better way to accomplish this is through dependency injection instead of global references. Cross injection is possible but again, it should be used sparingly. A better solution would be to refactor the classes to have linear dependencies.
Is there any concepts in Java that would reference the actual object (like a pointer) to the object as a variable instead of making a copy of the object?
Java is pass by value but the value of any Object is the reference to the object (similar to pointers in C although they are not a memory address). So if you have an instance of A and assign it to another field, that field will be the same value and will be referencing the same instance of A.
// instantiate a new instance of A
A a1 = new A();
// assign the reference to A to another variable
a2 = a1;
// they are equivalent and both reference the same object
if (a1 == a2) ...
Is there any concepts in Java that would reference the actual object (like a pointer) to the object as a variable instead of making a copy of the object?
Actually, Java has only references. A variable can't contain an object, so no worries there.
Also, instead of doing
private ClassB b = Baseclass.B;
I'd suggest you consider doing a static import:
import static some.package.Baseclass.*;
When you make a reference in Java you are actually making a copy of a reference. You aren't copying Baseclass.B in your example. You're copying a reference to Baseclass.B.
In the example code you have provided, b is going to be null until Baseclass.B is defined. If you need to do an operation on b, you can't do it in the declaration of ClassA. You need to do it in a method that is called after object a has been created.
This is a classic application for a singleton.
For each one:
Make the constructor private.
Add a private static member of the class's own type to hold the
singleton.
Add a "getThe()" method which initializes the above member if it's not already set.
See wikipedia:Singleton pattern.
Make the constructor of A construct B also, by doing a getThe() on it.
Also, don't use public fields in Baseclass; instead use public getter methods. Don't keep a separate B variable; instead, ask the A singleton for it.
Is there any concepts in Java that would reference the actual object
(like a pointer) to the object as a variable instead of making a copy
of the object?
When you do this:
private ClassB b = Baseclass.B;
Really you are ponting at the same object a it's because the "b" variable is named Reference Variable.
About your question, my recomendation is do something like this:
First encapsule the reference:
public class ClassA{
private ClassB b;
public void setB(ClassB b) {
this.b = b;
}
public ClassB getB(ClassB b) {
return this.b;
}
}
Second use an static block for init the variables:
public class Baseclass{
public static ClassA A = new ClassA();
public static ClassB B = new Classb();
static {
A.setB(B);
B.setA(A);
}
}

Accessibility of members of top level class in inner class?

I have a query regarding accessibility of top level class from member inner class.
I have just read the reason why local or anonymous inner classes can access only final variables.The reason being JVM handles these two classes as entirely different classes and so, if value of variable in one class changes, it can't be reflected at run time in another class file.
Then, my question is that how an inner member class (non-static) can have access to members to members of top level class, as JVM is still treating these two classes as different class files? If value of a member variable of top level class changes, how will it possible to reflect in class file of inner class at runtime?
They're separate classes, but there's an implicit reference to the instance of the "outer" class in the "inner" class. It basically acts as a variable which you can get at either implicitly or via special syntax of ContainingClassname.this.
Note that if you don't want such an implicit reference, you should declare the nested class as static:
public class Outer
{
private class Inner
{
// There's an implicit reference to an instance of Outer in here.
// For example:
// Outer outer = Outer.this;
}
private static class Nested
{
// There's no implicit reference to an instance of Outer here.
}
}
this is implicitly final, you cannot change it. When you write some thing like
class Outer {
int a;
class Inner {
{ a = 1; }
}
}
you are actually writing the same as
class Outer {
int a;
class Inner {
{ Outer.this.a = 1; }
}
}
The a is not final but the Outer.this is, and that is the reference which is used.

Categories

Resources