Example creating object of a class:
public class Class_One {
int xx = 5;
public void methodA() {
int yy=10;
System.out.println("This is
inside Class_One.");
System.out.println("This is value
of yy = " +yy);
}
public static void main(String[] args) throws Exception {
Class_One
A = new Class_One();
int aa = A.xx;
System.out.println("aa = " +aa);
A.methodA();
}
}
Output:
aa = 5
This is inside Class_One.
This is value of yy = 10
Class as DataType:
public class Class_One {
int xx = 5;
public void methodA() {
System.out.println("This is
inside Class_One.");
}
}
public class Class_Two {
int i = 10;
public void methodA(Class_One c)
{
System.out.println("This is
inside Class_Two.");
c.methodA();
System.out.println("Value of xx
from Class_One = " + c.xx);
}
public static void main(String[] args) throws Exception {
Class_Two
pc = new Class_Two();
pc.methodA(new Class_One());
}
}
Output:
This is inside Class_Two.
This is inside Class_One.
Value of xx from Class_One = 5
Above code can also be written as :
public class Class_One {
int xx = 5;
public void methodA() {
System.out.println("This is
inside Class_One.");
}
}
public class Class_Two {
int i = 10;
public static void methodA(Class_One c)
{ //added static
System.out.println("This is
inside Class_Two.");
c.methodA();
System.out.println("Value of xx
from Class_One = " + c.xx);
}
public static void main(String[] args) throws Exception {
methodA(new Class_One()); //removed object of
the class two
}
}
Output:
This is inside Class_Two.
This is inside Class_One.
Value of xx from Class_One = 5
No comments:
Post a Comment