Classes and Objects in Java

Class, method and constructor

1

Adding Methods
class trial { int a=8,b=9; void cal() { int c = a*b; System.out.println("c= "+c); } } class TrialDemo1 { public static void main(String arg[]) { trial t = new trial(); t.cal(); } }
2

Program
class trial { int a,b; void cal(int m, int n) { a=m;b=n; int c = a*b; System.out.println("c= "+c); } } class TrialDemo2 { public static void main(String arg[]) { trial t = new trial(); t.cal(8,5); } }

3

class trial { int a,b; trial() //default constructor { a=9;b=6;} trial(int m, int n) // parameterized constructor { a=m;b=n;} trial(trial t2) // object as parameter { this.a=t2.a; this.b=t2.b;}

void cal() //method to multiply two nos and display { int c = a*b; System.out.println("c= "+c); }
}
4

class TrialDemo3 { public static void main(String arg[]) { trial t = new trial(); // default constructor trial t1 = new trial(3,4); //parameterized constructor trial t3 = new trial(t1);//object as a parameter t.cal();t1.cal();t3.cal();
} }

5

Sign up to vote on this title
UsefulNot useful