+ 5
When initiating objects in Java (such as A a = new A();), what is the difference between the first and second capital A?
I am aware that the first and last characters in the command deal with classes. In this case, those characters are A and A(). What do each of these actually represent (because sometimes they reference different classes)?
12 odpowiedzi
+ 7
First A creates a referance variable of class A, which can hold object of its class as well as of its sub-classes
Second A(), is followed by new, species that object of class A has to be made and its address is passed to the referance variable created by first A.
Super class reference variable can hold object refernce for the same class along with its sub classes but sub class reference variable can not hold object reference of super classes.
e.g..
class A{}
class B extends A{}
now in this case,
A aa= new A(); // valid
A ab= new B(); // valid called composition
B ba=new A(); // not valid
B bb=new B(); // valid
I hope you understand, if not, then let me know...
Happy learning...
+ 7
A is the class.
a is the object of class A.
So ::
A a = new A();
is simply saying that
a is an object of the class A
A clearer example
===============
Animals Cat = new Animal();
You get the idea
+ 5
The first a (a), is an Object, while the second (A) represents a Class
+ 3
Jain Rishav Amit Thanks, it helps :)
+ 2
First 'A' say that 'a' is a var of class 'A'
Second 'A' its a reference (called) to 'A' constructor
+ 2
D'lite Ok, thanks. But what is the difference between the first and last "A"? As occasionally, they do not match.
Example: B a = new A();
+ 2
A is class name and small a is object name and right side of A name is constructor of the class A. we are taking constructor name class name same
+ 2
jain rishav it example is very clear great 😊
+ 1
First A is the Type (class) second one is the object
+ 1
The 'command' is declaration of variable a of class A with initial value (right part). new A() is actually a call to special class method - constructor. Constructor allocates memory for new class instance and assigns initial values of instance internal variables. Syntax A() means empty list of constructor parameters in this case but class can declare many constructors with different initialisation parameters. Subclass constructor always calls some superclass constructor before subclass initialisation. Explicitly superclass constructor without parameters used but you can specify parameters for superclass construction and appropriate superclass constructor will initialize superclass part of your subclass instance.
+ 1
d'lite read the example giving by the rishav .