The Artima Developer Community
Sponsored Link

Legacy Design Forum
Composition Versus Inheritance

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Initializers are Run When Objects are Created

Posted by Bill Venners on April 21, 2000 at 2:41 PM

> Could you explain to me the logic of the output as given by the foll. program : (I am terribly confused by private Circle c1=new Circle(100); line - When is it executed ???)
> Thanks,
> Radhey
> *************
> import java.util.*;

> class Shape {
> Shape(int i) {
> System.out.println("Shape constructor"+"-->"+i);
> }
> }

> class Circle extends Shape {
> Circle(int i) {
> super(i);
> System.out.println("Drawing a Circle"+"-->"+i);
> }
> }

> public class rss extends Shape {
> private Circle c;
> private Circle c1=new Circle(100);
> rss(int i) {
> super(i + 1);
> c = new Circle(1);
> System.out.println("Combined constructor");
> }
>
> public static void main(String[] args) {
> rss x = new rss(47);
> }
> }

The statement:

private Circle c1=new Circle(100);

is executed when your main() method instantiates the
rss object, becuase c1 is an instance variable of the
rss object, initialized by the new Circle(100) initializer.

bv



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us