Class
Collection of objects is called class. It is a logical entity.
Instance variable in Java
A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn’t get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
package com.hotmail.henrytien;
public class Calculation {
void fact(int n) {
int fact = 1;
for(int i=1;i<=n;i++) {
fact = fact*i;
}
System.out.println("factorial is "+ fact);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Calculation().fact(5); // calling method with annonymous object
}
}
output:factorial is 240
Creating multiple objects by one type only
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Example of Method Overloading with TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
public static void main(String args[]){
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
In this example,we are going to copy the values of one object into another using java constructor.
package com.hotmail.henrytien;
public class Student3 {
int id;
String name;
Student3(int i,String n){
id = i;
name = n;
}
Student3(Student3 s){
id = s.id;
name = s.name;
}
void dispaly() {
System.out.println(id+" "+name);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student3 s1 = new Student3(120,"wang");
Student3 s2 = new Student3(s1);
s1.dispaly();
s2.dispaly();
}
}
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
package com.hotmail.henrytien;
public class Student3 {
int id;
String name;
Student3(int i,String n){
id = i;
name = n;
}
Student3(){
}
void dispaly() {
System.out.println(id+" "+name);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student3 s1 = new Student3(120,"wang");
Student3 s2 = new Student3();
s2.id = s1.id;
s2.name= s1.name;
s1.dispaly();
s2.dispaly();
}
}