Lecture 6 and 7 - Constructors , Objects , Key features of OOP Flashcards
What is a java constructor?
constructor is invoked at the time of object creation. It constructs the values i.e. initialises data for the object.
Constructors could also be overloaded.
Must for a constructor:
name must be same as its class name
must have no explicit return type
What happens if a constructor is omitted in the class?
In this case, the compiler automatically create a default no-arg constructor.
How do you create an object?
Examples
Rectangle rectSmall = new Rectangle();
or:
Rectangle rectLarge;
rectLarge = new Rectangle(10.0,15.0);
Steps for creating an object:
Declaration
Instantiation
Initialization
Accessing instance members (i.e, attributes and methods):
Explain instantiation:
The new keyword is used to create the object, i.e., a block of memory space is allocated for this object.
Explain initialization:
The new keyword is followed by a call to a constructor which initializes the new object.
Explain how to access instance members:
First, create an instance/object of the class;
Then, use the dot operator (.) to reference the member
attributes or member methods
ex. Rectangle rect1 = new Rectangle(10,15,2,4);
double w = rect1.width;
rect1.move(2.5,0);
double area = new Rectangle(10,15).getArea();
What can instance methods do ?
can access instance attributes and instance methods directly.
can access static attributes and static methods directly.
What can static methods do and not do ?
can access static attributes and static methods directly.
CANNOT access instance attributes or instance methods directly, they must use an object reference.
CANNOT use the this keyword as there is no instance for this to refer to
The arguments of a method could be:
Primitive Data Type
Reference Data Type (Class, interface, array, enum)
Explain passing by value :
The method gets a copy of the variable you pass. If you change the copy inside the method, the original value remains the same.
What is auto-boxing and unboxing
Autoboxing Converting a primitive value (an int, for
example) into an object of the corresponding wrapper class(Integer).
Unboxing Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value.
How does java apply auto-boxing and unboxing?
Assignment
Method invocation