Creating Objects Using Constructors new Classnameo Example new Circle new Circle(5.0) Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 11 Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);
Default constructor a class may be declared without constructors. In this case, a no-arg constructor with an empt body is implicitly declared in the class. This constructor. called a default constructor is provided automatically only if no constructors are explicitly declared in the class Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 12 Default Constructor A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class
Constructing objects, cont Circle UML Graphical notation for classes radius: double UML Graphical notation for fields UML Graphical notation for method findAreaO: double new circle( new circle circle/. Circle circlen: Circle K.ML Graphical notation for objects radius= 2 radius=5 Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 13 Constructing Objects, cont. circle1: Circle radius = 2 new Circle() circlen: Circle radius = 5 new Circle() ... UML Graphical notation for classes UML Graphical notation for objects Circle radius: double findArea(): double UML Graphical notation for fields UML Graphical notation for methods
Declaring Object Reference Variables To reference an object assign the object to a reference variable To declare a reference variable, use the syntax ClassName objectrefvar Example Circle mycircle' Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 14 Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;
Declaring/Creating Objects in a single ster ClassName objectRefvar= new ClassNameo Assign object reference Create an object Example Circle mycircle fnew Circle; Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 15 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference