Classes and Objects CGS3416 Spring 2019
Classes Class is a blueprint for objects. A class is a user-defined type that describes and defines objects of the same type. A class contains data values and methods.
Data values
Objects and References
Objects
Creating an object from a class
References
Objects and References Object: an instance of a class Class: a template or blueprint from which individual objects are created Instantiation: the creation of an object class objName = new Constructor(); The constructor will always have the same name as the class Person sally = new Person();
Constructor A constructor is used to initialize an object (variables and call methods). Get objects of a class ready for use Same name as the class No return type
Type of constructor Default constructor Parameterized constructor
Method overloading Demo In Java it is possible to define two or more methods within the same class that are having the same name, but their parameter declarations are different. In the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways of java implementation of polymorphism. Demo
Constructors overloading vs Method overloading Strictly speaking, constructor overloading is somewhat similar to method overloading. If we want to have different ways of initializing an object using different number of parameters, then we must do constructor overloading as we do method overloading when we want different definitions of a method based on different parameters.
Constructor overloading Demo (Box and BoxRunner)
Protection levels in a class
Data Hiding
Demo (Student and StudentRunner)
Accessor and mutator methods Instance variables should be declared with the keyword private Data hiding is the main reason for the private declaration Accessor methods allow an outside class to READ instance variables Accessor methods often times start with the word get and can be called getters Mutator methods allow an outside class to WRITE instance variables Mutator methods often times start with the word set and can be called setters
Demo (Account and AccountRunner)
The ‘this’ keyword Many times it is necessary to refer to its own object in a method or a constructor. To allow this Java defines the ‘this’ keyword. The ‘this’ is used inside the method or constructor to refer its own object That is, ‘this’ is always a reference to the object of the current class type.