Java Class, Objects, Methods, Constructor example – part 2

Example 6:
class AB{
int k;
String name;

void display(){
AB ab=new AB();
ab.k=56;
System.out.println(ab.k);

}

}

class A{
public static void main(String[] args){

AB ab=new AB();
ab.display();

System.out.println(ab.k);
}
}

Note* : Save, Compile and Execute
Output:
56
0 

Example 7:

class AB{
int k;
String name;

void display(){
AB ab=new AB();
ab.k=56;
ab.name=”Oxyzium”;
System.out.println(“In display: “+ab.k);
System.out.println(“In display: “+ab.name);
}

void print(){
System.out.println(“In print: “+k);
System.out.println(“In print: “+name);
}

}

class A{
public static void main(String[] args){

AB ab=new AB();
ab.display();
ab.print();

}
}

Note* : Save, Compile and Execute
Output:
In display : 56
In display : Oxyzium
In print: 0
In print: null

Example 8:

class AB{

AB(){
System.out.println(“I am in cons”);

}

void print(){
System.out.println(“I am in print()”);
}

}

class A{
public static void main(String[] args){

new AB().print();

}
}

Note* : Save, Compile and Execute
Output:
I am in cons
I am in print()

Example 9:

class AB{
int a=80;
static int b=20;
}

class A{
public static void main(String[] args){

AB ab1=new AB();

System.out.println(AB.b*ab1.a);
}
}

Note* : Save, Compile and Execute
Output:
1600

Example 10:

class AB{
int a=15;//instance field
static int b;//class field
}

class A{
public static void main(String[] args){
System.out.println(new AB().a);
System.out.println(AB.b);
}
}

Note* : Save, Compile and Execute
Output:
15
0