Chapter5_2-Methods

The default constructor does not accept parameters

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: s of objects when they are created. • ClassName x = new ClassName(); • A class contains at least one constructor. • A class may contain more than one constructor. Page 31 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP The Default Class Constructor • If no constructors are defined in the class, the default constructor is added by the compiler at compile time. • The default constructor does not accept parameters and creates objects with empty states. • ClassName x = new ClassName(); Page 32 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP Class Constructors Declaration public <constructor name> ( <parameters> ){ <constructor body> } • The constructor name: a constructor has the name of the class . • The parameters represent values that will be passed to the constructor for initialize the object state. • Constructor declarations look like method declarations— except that they use the name of the class and have no return type. Page 33 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP Example of a Constructor with No-Parameter public class Kasree { A. The instance A. The instance A. private int bast; private int maquam; Object: Kasree B. The object is B. The object is B. public Kasree() { bast = 0; maquam =1; x variable is allocated variable is allocated in memory. in memory. created with initial state created with initial state 0 1 bast maquam } ... C. The reference of the C. The reference of the C. } x object created in B is object created in B is assigned to the variable. assigned to the variable. A A B B Kasree x; Object: Kasree bast x = new Kasree ( ) ; C C Code Page 34 maquam 0 1 State of Memory Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online