Summary
When you define a new class, you declare its name with the
classkeyword, and then define its methods, fields, and properties.To instantiate an object, you declare the name of the class, followed by an identifier for the object, much as you would a local variable. You then need to allocate memory for the actual (unnamed) object that will be created on the heap; you do so with the keyword
new.You invoke a method on an object by writing the name of the object, followed by the dot operator, and the method name followed by parentheses. Parameters, if any, are placed within the parentheses.
Access modifiers dictate which methods of external classes can see and use a variable or method within a class. All members of the class are visible to all methods of its own class.
Members marked
publichave no restrictions, and are visible to methods of any class.Members marked
privateare visible only to methods within the same class.Members marked
protectedare visible to methods within the same class, and methods in derived classes.If you know the return type of a method, you can use a method call anyplace you would use an instance of that type.
A constructor is a special method invoked when a new object is created. If you do not define any constructors at all for your class, the compiler will provide a default constructor that does nothing. A default constructor is a constructor that takes no parameters. You are free to create your own default constructor for your class.
You can initialize ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access