50 likes | 216 Views
Constructors. Used to initialize the member variables Default constructor initializes these to zero Constructors are special type of methods Do not have a return type (not even void) Must be public so that they can be accessed from a different class
E N D
Constructors • Used to initialize the member variables • Default constructor initializes these to zero • Constructors are special type of methods • Do not have a return type (not even void) • Must be public so that they can be accessed from a different class • Cannot be static: static methods can be invoked without attaching them to any object e.g., main; constructors by definition must be invoked for a particular object
class example class Pwr { double b; int e; double val; Pwr(double base, int exp) { b = base; e = exp; val = 1; if(exp==0) return; for( ; exp>0; exp--) val = val * base; } double get_pwr() { return val; } } class power { public static void main(String args[]) { Pwr x = new Pwr(4.0, 2); Pwr y = new Pwr(2.5, 1); Pwr z = new Pwr(5.7, 0); System.out.println(x.b + " raised to the " + x.e + " power is " + x.get_pwr()); System.out.println(y.b + " raised to the " + y.e + " power is " + y.get_pwr()); System.out.println(z.b + " raised to the " + z.e + " power is " + z.get_pwr()); } }
‘this’ example class Pwr { double b; int e; double val; Pwr(double base, int exp) { this.b = base; this.e = exp; this.val = 1; if(exp==0) return; for( ; exp>0; exp--) this.val = this.val * base; } double get_pwr() { return this.val; } } class powerthis { public static void main(String args[]) { Pwr x = new Pwr(4.0, 2); Pwr y = new Pwr(2.5, 1); Pwr z = new Pwr(5.7, 0); System.out.println(x.b + " raised to the " + x.e + " power is " + x.get_pwr()); System.out.println(y.b + " raised to the " + y.e + " power is " + y.get_pwr()); System.out.println(z.b + " raised to the " + z.e + " power is " + z.get_pwr()); } }
‘this’ demo class Pwr { double b; int e; double val; Pwr(double b, int e) { this.b = b; this.e = e; val = 1; if(e==0) return; for( ; e>0; e--) val = val * b; } double get_pwr() { return this.val; } } class thisdemo { public static void main(String args[]) { Pwr x = new Pwr(4.0, 2); Pwr y = new Pwr(2.5, 1); Pwr z = new Pwr(5.7, 0); System.out.println(x.b + " raised to the " + x.e + " power is " + x.get_pwr()); System.out.println(y.b + " raised to the " + y.e + " power is " + y.get_pwr()); System.out.println(z.b + " raised to the " + z.e + " power is " + z.get_pwr()); } }
Class demo class C{ int x=10, y=25; C(){ } C(int a, int b){ //System.out.println("printining from constructor"+x+" "+y); x=a; y=b; } void f(int x){ System.out.println(x+" "+this.x+" "+y); C d = new C(1,1); System.out.println(d.x+" "+this.x+" "+d.y); d = this; System.out.println(d.x+" "+this.x+" "+d.y); } } class classdemo{ public static void main(String args[]){ C a = new C(); a.f(5); C b = new C(15,20); b.f(10); } } 5 10 25 1 10 1 10 10 25 10 15 20 1 15 1 15 15 20