OOP Concepts in Java11.0
The underlying concept of Object-Oriented Programming (OOP) is not far-fetched; as humans in today's world, we do experience and employ the concept of OOP in some (if not most) of our daily routines and/or activities. A typical real-world exemplification of the concept of Object-Oriented Programming can be illustrated using the mobile-phone technology.
Thus, every cellphone, irrespective of its make/brand, possesses a set of attributes (e.g. color, size, weight, screen-type, keypad, ports, etc.) and a set of functions (e.g. video-calling, modem, SMS, calculator, voice-messaging, compass, gyrometer, etc.); and which are both defined as members within the generic class for cellphone.
Therefore, whenever a make/brand gets approval to manufacture cellphones, they are issued with a license that incorporates the generic class template for cellphones. This licensed make/brand can create several models (typically objects) of the cellphone class, which are actually prototypes of the cellphone class, and they
market these models (or objects) for end-user purchase/acquisition. To this end, every cellphone (iPhone 13, Galaxy S23, Pixel 7, etc.) in the public market today is essentially a model/prototype (or object) of the generic class definition for a cellphone.
Additionally, another typical example with reference to the concept of Object-Oriented Programming (OOP) can be illustrated using the automobile technology. Every car/automobile, irrespective of its make/brand, possesses a set of attributes (such as color, weight, length, width, seats, etc.) and a set of functions
(such as self-drive, self-diagnostics, auto-parking, cruise-control, voice-command, keyless-start, etc.). Thus, these sets of attributes and functions are both defined as members within a generic class template for cars. So, whenever a new automobile manufacturer acquires the license to make cars or vehicles, they adopt the generic class template for cars.
Automobile brand(s) create and manufacture several models (or prototypes) of the generic class template for cars; and each of these models or prototypes is essentially an object of the car class template. Therefore, models such as Ford F-150, Tesla-Model-S, GMC Yukon, RAM 1500, etc., are all objects of the class template for cars.
11.1Introductory Terminologies to Object-Oriented Programming (OOP)
Caption: Driver class and Container class
- Class: A Java program that contains several definitions of attributes/fields/variables and functions/methods, and which can serve as a template for the creation of an object.
- Object: This is simply an instantiation, via the
new
keyword, of a class block (or segment).
- Driver Class: A Java project can contain several class (block) definitions. However, the class (block) that defines or contains the
main()
method is regarded as the Driver Class.
- Container Class: Within a Java project which can contain several class (block) definitions. The classes that do not contain or define the
main()
method are regarded as the Container Classes.
-
this
keyword: This is a virtual (object) reference, used during the implementation of a class block, to point/refer to only instance-based members (Constants, Variables, Methods, Constructors, etc.) available to an object of the class block.
In other words, the this
keyword cannot be used during the implementation of a class to point/refer to static-based members of the class.
-
Access Modifier: This is a keyword which is reserved for regulating the visibility of members (such as attributes/fields/variables, functions/methods, classes, etc.) with respect to OOP paradigm.
It can either be
private
, package-private
(default), protected
, or public
.
Access Modifier |
Scope and/or Visibility |
Class |
Package |
Subclass (via extends ) |
Global (anywhere) |
private |
Yes |
No |
No |
No |
package-private |
Yes |
Yes |
No |
No |
protected |
Yes |
Yes |
Yes |
No |
public |
Yes |
Yes |
Yes |
Yes |
public class OOPConceptsinJava {
//private: Both 'var1' and 'method1()' are only accessible within its (host) class block.
private int var1;
private void method1() { }
//package-private: Both 'var2' and 'method2()' are only accessible to all classes within its package (in a Java project).
int var2;
void method2() { }
//protected: Both 'var3' and 'method3()' are accessible to all classes within its package;
//and it also accessible to subclasses (in another package) inheriting from its (host) class.
protected int var3;
protected void method3() { }
//public: Both 'var4' and 'method4()' are accessible to every class, package, project, etc., within a Java project.
public int var4;
public void method4() { }
}
Code Snippet 1: Access modifiers with respect to OOP in Java
Furthermore, in Object-Oriented Programming paradigm, the standard practice involves designing classes such that each class is comprised of attributes or variables (which constitute the
Private Data aspect of the class) and functions or methods (which make up the
Public Interface of the class).
Also, the
Public Interface of a class encompasses those members of the class associated with a
public
access modifier; and the
Private Implementation (or
Interface) of a class includes all the class' members bearing a
private
access modifier.
Therefore, access to an OOP class (or its object) can only be via its
Public Interface. The Private Data and the Public Interface of a class can be implemented either as
instance members or
static members of the OOP class. In other words, the attributes/variables as well as the function/methods of an OOP class can either be
instance or
static members of the class.
Instance member
- This can be either a variable or a method defined within a class block.
-
In order to make a call to this member; an instance or object of the (host) class block must be declared and initialized using the
new
keyword.
Actually, this instance or object is like a virtual copy of the (host) class block; and it serves as a "gateway" to accessing all the instance-based variables and methods defined within the class block.
- A call to this type of member is usually with reference to the instance or object of the (host) class block.
Static member
- This can be either a variable or a method, which is defined within a class block, via explicit specification of the
static
keyword or modifier.
-
In order to make a call to this type of member, an instance/object of the (host) class block is never required.
The (host) class block permits direct access to all static-based variables and methods defined within it.
- Any call to this type of member is usually with direct reference to the (host) class block.
Caption: Relationship between Instance members and Static members with respect to the object of a class
On one hand, upon the instantiation of a class block, each created object possesses a unique copy of every instance-based member of that class. Thus, any update made to an instance-based member is limited to the specific object that initiated the update.
On the other hand, no object instantiated from a class can possess any static-based member. All static-based members are bound to the (host) class. Thus, any update made to a static-based member is effected in the (host) class itself.
Exercise 1: With regard to the concept of OOP, implement a Java program that will be responsible for taking attendance of individuals present in an auditorium.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class AttendanceContainer { //"Container" class
//"Static" attribute/variable
private static int centerMaxCap; //Bound to (host) class = "AttendanceContainer"
//"Instance" attribute/field/variable
private int attendCount; //Bound to any new object
//"Static" function/method
public static void setCenterCap(int cap) { //Bound to (host) class = "AttendanceContainer"
AttendanceContainer.centerMaxCap = cap;
}
//"Instance" function/method
public void setCountByIncrement() { //Bound to any new object
this.attendCount++;
}
//"Instance" function/method
public double getAttendancePercent() { //Bound to any new object
double localVar = (double) this.attendCount / (double) AttendanceContainer.centerMaxCap;
return localVar * 100;
}
}
Container class: Designing and implementing a class with respect to OOP techniques
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class AttendanceDriver { //"Driver" class
public static void main(String[] args) {
//Accessing a "static" method resident in the "AttendanceContainer" class
AttendanceContainer.setCenterCap(10);
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec1 = new AttendanceContainer();
sec1.setCountByIncrement(); //1st attendeee
sec1.setCountByIncrement(); //2nd attendeee
sec1.setCountByIncrement(); //3rd attendeee
sec1.setCountByIncrement(); //4th attendeee
sec1.setCountByIncrement(); //5th attendeee
System.out.println("Attendance rate for Sec1 is = " + sec1.getAttendancePercent() + "%");
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec2 = new AttendanceContainer();
sec2.setCountByIncrement(); //1st attendeee
sec2.setCountByIncrement(); //2nd attendeee
System.out.println("Attendance rate for Sec2 is = " + sec2.getAttendancePercent() + "%");
}
}
Driver class: Designing and implementing a class with respect to OOP techniques
Alternatively, it is possible to have both the Container class and the Driver class existing within the same source (.java) file. In that regard, it is important to note, there can exist at most only one (1) class block bearing the
public
access modifier in any given Java source code (or .java file).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
class AttendanceContainer { //"Container" class with package-private access modifier
//"Static" attribute/variable
private static int centerMaxCap; //Bound to (host) class = "AttendanceContainer"
//"Instance" attribute/field/variable
private int attendCount; //Bound to any new object
//"Static" function/method
public static void setCenterCap(int cap) { //Bound to (host) class = "AttendanceContainer"
AttendanceContainer.centerMaxCap = cap;
}
//"Instance" function/method
public void setCountByIncrement() { //Bound to any new object
this.attendCount++;
}
//"Instance" function/method
public double getAttendancePercent() { //Bound to any new object
double localVar = (double) this.attendCount / (double) AttendanceContainer.centerMaxCap;
return localVar * 100;
}
}
public class AttendanceDriver { //"Driver" class with public access modifier
public static void main(String[] args) {
//Accessing a "static" method resident in the "AttendanceContainer" class
AttendanceContainer.setCenterCap(10);
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec1 = new AttendanceContainer();
sec1.setCountByIncrement(); //1st attendeee
sec1.setCountByIncrement(); //2nd attendeee
sec1.setCountByIncrement(); //3rd attendeee
sec1.setCountByIncrement(); //4th attendeee
sec1.setCountByIncrement(); //5th attendeee
System.out.println("Attendance rate for Sec1 is = " + sec1.getAttendancePercent() + "%");
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec2 = new AttendanceContainer();
sec2.setCountByIncrement(); //1st attendeee
sec2.setCountByIncrement(); //2nd attendeee
System.out.println("Attendance rate for Sec2 is = " + sec2.getAttendancePercent() + "%");
}
}
Container class and Driver class: Designing and implementing classes with respect to OOP techniques
11.2Recursive Methods (or Functions)
Basically, a recursive method (or function) is an implementation technique that is employed with respect to the design and development of a method or function; such that one or more
return
statement(s) within the body of the method initiates a repetitive call to the same method itself.
To this end, the following principles and/or explanations apply to a recursive method, viz:
- Alternatively, a recursive method can be considered as a function that calls itself repeatedly.
- When a recursive method recalls itself during its execution or runtime; it does so by passing simpler arguments (or values) into its recursive calls.
- For a recursion to terminate, with reference to a recursive method, there must exist a special case or condition where the recursive method only accepts and processes the simplest arguments (or values).
In this regard, utmost precaution has to be taken when implementing a recursive method or function; otherwise, failure to adhere to the principles governing the implementation of a recursive method could result in an infinite loop/repetition.
Thus, the following conditions must be observed, so as to prevent an infinite loop with respect to the execution of a recursive method/function.
- Every repetitive call, within the implementation of a recursive method, must accept simpler arguments or values.
- There must exist a special case, within the implementation of a recursive method, such that passing the simplest arguments (or values) results in the termination of the recursion.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
public static void main(String[] args) {
OOPConceptsinJava obj1 = new OOPConceptsinJava();
System.out.println("Final result = " + obj1.recurFunc(1));
//Dry-run: Hand tracing output (start)
/*
---------------------------------------------
| Iteration | RETURN
---------------------------------------------
| 1 | 1 + recurFunc(2)
| 2 | 1 + 2 + recurFunc(4)
| 3 | 1 + 2 + 4 + recurFunc(8)
| 4 | 1 + 2 + 4 + 8 + recurFunc(16)
| 5 (final) | 1 + 2 + 4 + 8 + 10
---------------------------------------------
Final result = 25
*/
//Dry-run: Hand tracing output (stop)
}
//Instance method
public int recurFunc (int i) {
if (i >= 10) {
return 10;
}
return i + recurFunc (i * 2);
}
}
Code Snippet 1: Hand tracing a recursive method implementation
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
public static void main(String[] args) {
OOPConceptsinJava obj1 = new OOPConceptsinJava();
System.out.println("Final result = " + obj1.sumPrev2(5));
//Dry-run: Hand tracing output (start)
/*
---------------------------------------------
| Iteration | RETURN
---------------------------------------------
| 1 | [sumPrev2(4)] + [sumPrev2(3)]
| 2 | [sumPrev2(3) + sumPrev2(2)] + [sumPrev2(2) + sumPrev2(1)]
| 3 | [sumPrev2(2) + sumPrev2(1) + sumPrev2(1) + sumPrev2(0)] + [sumPrev2(1) + sumPrev2(0) + 1]
| 4 | [sumPrev2(1) + sumPrev2(0) + 1 + 1 + 0] + [1 + 0 + 1]
| 5 (final) | [1 + 0 + 1 + 1 + 0] + [1 + 0 + 1] == 5
---------------------------------------------
Final result = 5
*/
//Dry-run: Hand tracing output (stop)
}
//Instance method
public int sumPrev2 (int i) {
if ((i == 0) || (i == 1)) { //Special Case (based on simplest arguments)
return i;
}
else {
return sumPrev2(i - 1) + sumPrev2(i - 2);
}
}
}
Code Snippet 2: Hand tracing a recursive method implementation
11.3Pillars of Object-Oriented Programming
The underlying principles of Object-Oriented Programming are centered on the following essential pillars, namely:
-
Abstraction: This entails creating one or more Container classes, with the aim of separating the program's complexity, from the Driver class. Thus, the Driver class simply acts as an interface that obscures the fundamental logic of the program contained within the Container classes.
Real-world Example: We do use cellphones, and we do so without concern(s) about the internal operations of the cellphone. Our focus is essentially on how to operate the phone via its user-interface(s) such as keypad, screen, etc. In this regard, our knowledge of the cellphone is simply abstract.
-
Encapsulation: This is a "Separation of Concern" technique that involves wrapping different functionalities (of a program) into different methods/functions, and which are implemented within one or more classes. In other words, Encapsulation comprises implementation hiding (with the aid of methods/functions) and information hiding (via access modifiers).
Real-world Example: This concept can be exemplified using a prescription capsule (drug). A capsule encloses the active ingredients of a drug within a water-soluble container; and when we ingest this capsule, the capsule's container dissovles to release its encapsulated active ingredients into our body for the effective treatment of the illness.
-
Inheritance: Just as the name implies, it involves a subclass (child) acquiring attributes and/or functions from a superclass (parent).
Real-world Example: This is similar to the natural parent-to-child transfer of (desirable) traits with respect to reproduction in humans and/or animals.
-
Polymorphism: This involves defining methods (or functions) which behave and/or respond differently with respect to varying programmatic contexts. In this regard, Polymorphism is essentially achieved in OOP paradigm via Overloading.
The concept of Overloading enables a member (in OOP context) carry out different tasks with respect to different contexts.
Real-world Example: In Java programming, the addition operator (+
) is an overloaded and polymorphic operator such that it can perform either a numeric-addition operation or a concatenation operation depending on the content of its binary operands.
Caption: Parts of a method or function
The following steps should be adhered to when designing and implementing a class (block) with respect to Object-Oriented Programming paradigm, viz:
-
Specify the Public Interface:
- What tasks will the class (block) perform with respect to its implementation?
- What methods with
public
access modifier will be required within the class?
- What parameters will these
public
methods accept?
- What values or data will the
public
methods return?
- State the comments associated with each
public
method?
-
Specify the Private Implementation:
- Declare the data (variables and/or constants) of the class which will possess
private
access modifiers.
- Define the body of each method contained within the class (block).
11.4Types of Methods (or Functions) in Object-Oriented Programming
With respect to the concept of OOP, a method/function in Java programming can be categorized as either of the following, viz:
-
Accessor (or Getter) method:
- A type of method that may possess one or more parameters; and this method can neither change nor update the (data) content of the attributes (variables and/or constants) in an object or a class.
- Only requests for data, from an object or a class, without changing or updating it.
- It usually returns a value of a specific data type.
- For example, consider the following method header of an Accessor/Getter method:
public double getResult () { }
-
Mutator (or Setter) method:
- This usually possesses one or more parameters; and these parameters are usually employed with respect to changing or updating the (data) content of the attributes (variables and/or constants) in an object or a class.
- Always changes or updates the attributes of an object or a class.
- It usually returns:
void
.
- For example, consider the following method header of a Mutator/Setter method:
public void addScore (double score) { }
-
Constructor:
- This is a special type of method with reference to the concepts of OOP.
- A constructor is responsible for initializing the instance-based attributes (variables and/or constants) of an object during its creation.
- It is automatically invoked, using the
new
keyword, whenever an object (of a class) is being created or instantiated.
- It cannot be implemented as a
static
method of a class.
- It must possess exactly the same name as the class.
- It must not return a (data) value; and the
void
keyword should not be specified in its header.
- A class (block) may implement several constructors (bearing exactly same name as the class), but with different parameter lists.
-
In this regard, the following types of constructors can be implemented with respect to OOP, viz:
//DEFAULT constructor
public <className>() {
//Body of the DEFAULT constructor
}
//CUSTOM constructor
public <className>(int parameter1, String parameter2) {
//Body of a CUSTOM constructor
}
//COPY constructor
public <className>(<className> parameterOfClassDataType) {
//Body of a COPY constructor
}
Code Snippet: Types of Constructors with respect to Object-Oriented Programming (OOP)
Furthermore, the following code snippets showcase some implementations of Constructors with respect to Object-Oriented Programming in Java.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class AttendanceContainer { //"Container" class
//"Static" attribute/variable
private static int centerMaxCap; //Bound to (host) class = "AttendanceContainer"
//"Instance" attribute/field/variable
private int attendCount; //Bound to any new object
//DEFAULT constructor
public AttendanceContainer() {
this.attendCount = 0;
}
//CUSTOM constructor
public AttendanceContainer(int initVal) {
this.attendCount = initVal;
}
//COPY constructor
public AttendanceContainer(AttendanceContainer objOfClass) {
this.attendCount = objOfClass.attendCount;
}
//"Static" function/method
public static void setCenterCap(int cap) { //Bound to (host) class = "AttendanceContainer"
AttendanceContainer.centerMaxCap = cap;
}
//"Instance" function/method
public void setCountByIncrement() { //Bound to any new object
this.attendCount++;
}
//"Instance" function/method
public double getAttendancePercent() { //Bound to any new object
double localVar = (double) this.attendCount / (double) AttendanceContainer.centerMaxCap;
return localVar * 100;
}
}
Container class: Designing and implementing a class with respect to OOP techniques (inclusive of Constructors)
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class AttendanceDriver { //"Driver" class
public static void main(String[] args) {
//Accessing a "static" method resident in the "AttendanceContainer" class
AttendanceContainer.setCenterCap(100);
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec1 = new AttendanceContainer(); //Call to DEFAULT constructor
sec1.setCountByIncrement(); //1st attendeee
sec1.setCountByIncrement(); //2nd attendeee
sec1.setCountByIncrement(); //3rd attendeee
sec1.setCountByIncrement(); //4th attendeee
sec1.setCountByIncrement(); //5th attendeee
System.out.println("Attendance rate for Sec1 is = " + sec1.getAttendancePercent() + "%");
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec2 = new AttendanceContainer(67); //Call to CUSTOM constructor
sec2.setCountByIncrement(); //68th attendeee
sec2.setCountByIncrement(); //69th attendeee
sec2.setCountByIncrement(); //70th attendeee
System.out.println("Attendance rate for Sec2 is = " + sec2.getAttendancePercent() + "%");
//Instantiating an object of the "AttendanceContainer" class
AttendanceContainer sec3 = new AttendanceContainer(sec2); //Call to COPY constructor
System.out.println("Attendance rate for Sec3 is = " + sec3.getAttendancePercent() + "%");
}
}
Driver class: Designing and implementing a class with respect to OOP techniques (inclusive of calls to Constructors)
With respect to Object-Oriented Programming paradigm in Java, all the attributes (variables and/or constants) of a class are usually intialized to a respective value during execution time (or runtime). In this regard, the instance-based attributes of a class are always initialized by the
DEFAULT constructor during each instantiation of an object from the class.
Also, the static-based attributes of a class are always initialized by the
Java Virtual Machine (JVM) during the
Load Time of each class. To this end, the following table highlights the initial value for any attribute (instance-based or static-based) of a class with respect to its data type.
Data Type of Attribute |
Initialization Value |
byte |
0 |
short |
int |
long |
float |
0.0 |
double |
char |
' ' |
boolean |
false |
String |
null |
Object |
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class AttendanceContainer { //"Container" class
//"Static" attribute/variable
//Initialized to zero (0) by the Java Virtual Machine (JVM) during "Load Time" of this class block
private static int centerMaxCap; //Bound to (host) class = "AttendanceContainer"
//"Instance" attribute/field/variable
//Initialized to zero (0) by a DEFAULT constructor (either explicitly defined by the programmer or implicitly defined by the JVM)
private int attendCount; //Bound to any new object
//"Static" function/method
public static void setCenterCap(int cap) { //Bound to (host) class = "AttendanceContainer"
AttendanceContainer.centerMaxCap = cap;
}
//"Instance" function/method
public void setCountByIncrement() { //Bound to any new object
this.attendCount++;
}
//"Instance" function/method
public double getAttendancePercent() { //Bound to any new object
double localVar = (double) this.attendCount / (double) AttendanceContainer.centerMaxCap;
return localVar * 100;
}
}
Container class: Initialization of the attributes in a class with respect to OOP techniques
11.5Overloading of Methods (or Functions) in Object-Oriented Programming
This is a technique employed towards implementing Polymorphism in Object-Oriented Programming; and it entails creating several methods (or functions) which all bear the same name, but with varying parameter lists.
//Method 1
public <methodName1>() {
//Body of method 1
}
//1: Overloaded Method
public <methodName1>(int parameter1, String parameter2) {
//Body of method 2
}
//2: Overloaded Method
public <methodName1>(int parameter1, int parameter2, double parameter3) {
//Body of method 3
}
//3: Overloaded Method
public <methodName1>(float parameter1, double parameter2) {
//Body of method 4
}
Code Snippet: Overloading of methods/functions with respect to Object-Oriented Programming (OOP)
Exercise 1: Implement a Java program, using the concepts of OOP, such that this program will be capable of storing the particulars of each student registered in a course.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
class Student { //"Container" class with package-private access modifier
private String fName;
private String lName;
private int regNum;
//DEFAULT Constructor will be implicitly invoked by JVM upon instantiation of any object
//Method
public String initStudent (String firN, String lasN, int regN) {
this.fName = firN;
this.lName = lasN;
this.regNum = regN;
return this.regNum + ": " + this.lName + ", " + this.fName;
}
//1: Overloaded Method
public String initStudent (String firN, int regN) {
this.fName = firN;
this.regNum = regN;
return this.regNum + ": " + this.fName + ", " + this.lName;
}
//2: Overloaded Method
public String initStudent (Integer regN) {
this.fName = regN.toString();
this.lName = regN.toString();
this.regNum = regN;
return this.regNum + " (" + this.fName + ", " + this.lName + ")";
}
}
public class StudentDriver { //"Driver" class with public access modifier
public static void main(String[] args) {
//Instantiate an object of "Student" class. DEFAULT Constructor is implicitly called by JVM.
Student stud1 = new Student();
//Call to initStudent(String, String, int) method
String s1 = stud1.initStudent("FirstName", "LastName", 40445055);
System.out.println(s1);
//Call to Overloaded Method: initStudent(String, int)
String s2 = stud1.initStudent("UpdateFirstName", 50554044);
System.out.println(s2);
//Call to Overloaded Method: initStudent (Integer)
String s3 = stud1.initStudent(60667077);
System.out.println(s3);
}
}
Container class and Driver class: Designing and implementing classes with respect to OOP techniques
11.6Practice Exercise
-
Given the following Java program with respect to OOP paradigm, do you think that this program will compile successfully and execute/run successfully too?
If yes, then state the exact screen output(s). If otherwise, then expantiate on the bug(s) as well as the type of error/bug herein.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
class AttendanceContainer {
private String uName;
public void dispStrProps() {
System.out.println("uName = " + this.uName);
System.out.println("Length of uName = " + this.uName.length());
}
}
public class AttendanceDriver {
public static void main(String[] args) {
AttendanceContainer obj1 = new AttendanceContainer();
obj1.dispStrProps();
}
}
-
With respect to the following program in OOP paradigm, do you think that this program will compile successfully and execute/run successfully too?
If yes, then state the exact screen output(s). If otherwise, then expantiate on the bug(s) as well as the type of error/bug herein.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
class AttendanceContainer {
private Integer val1;
public void dispIntProps() {
System.out.println("val1 = " + this.val1);
System.out.println("Length of val1 = " + this.val1.toString().length());
}
}
public class AttendanceDriver {
public static void main(String[] args) {
AttendanceContainer obj1 = new AttendanceContainer();
obj1.dispIntProps();
}
}
-
Do you think that the program below will compile successfully and execute/run successfully?
If yes, then state the exact screen output(s). If otherwise, then expantiate on the bug(s) as well as the type of error/bug herein.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
class AttendanceContainer {
private int val1;
public void dispIntProps() {
System.out.println("val1 = " + this.val1);
System.out.println("Magnitude of val1 = " + this.val1);
}
}
public class AttendanceDriver {
public static void main(String[] args) {
AttendanceContainer obj1 = new AttendanceContainer();
obj1.dispIntProps();
}
}
-
Given the following class (block) with respect to Object-Oriented Programming; what will be the initial values for all the attributes of this class (block) upon instantiation of an object of this class?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private int val1;
private static int val2;
private String val3;
private static String val4;
}
-
In the class block below, which of the following members constitute its Public Interface?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private int val1;
public static final String VAL2 = "A Constant!";
public String val3;
private static String val4;
private void dispProps() { }
public String dispIntProps(int param1) { }
public String dispStrProps(String param1) { }
}
-
In the class block below, which of the following members constitute its Private Implementation/Interface?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private int val1;
public static final String VAL2 = "A Constant!";
public String val3;
private static String val4;
private void dispProps() { }
public String dispIntProps(int param1) { }
public String dispStrProps(String param1) { }
}
-
Given the following class block, which of the its members is/are considered as Setter methods?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private static int centerMaxCap;
private int attendCount;
public static void gCenterCap(int cap) {
OOPConceptsinJava.centerMaxCap = cap;
}
public void gCountByIncrement() {
this.attendCount++;
}
public double mAttendancePercent() {
double localVar = (double) this.attendCount / (double) OOPConceptsinJava.centerMaxCap;
return localVar * 100;
}
}
-
Given the following class block, which of the its members is/are considered as Accessor methods?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private static int centerMaxCap;
private int attendCount;
public static void gCenterCap(int cap) {
OOPConceptsinJava.centerMaxCap = cap;
}
public void gCountByIncrement() {
this.attendCount++;
}
public double mAttendancePercent() {
double localVar = (double) this.attendCount / (double) OOPConceptsinJava.centerMaxCap;
return localVar * 100;
}
}
-
Which of the following options represents a valid Constructor with respect to the class block:
myClass
?
private myClass(int initVal) { }
private void myClass(int initVal) { }
private myClass() { }
public myClass(int initVal) { }
public static myClass() { }
public void myClass() { }
- TRUE or FALSE: A COPY Constructor is a valid type of Constructor with respect to Object-Oriented Programming (OOP)?
- TRUE or FALSE: Object-Oriented Programming (OOP) involves designing and developing class blocks (or segments) around the fundamental concepts of Abstraction, Encapsulation, Inheritance, and Polymorphism?
- TRUE or FALSE: A constructor is a special type of method which has exactly the same name as its (host) class, but cannot possess any parameter in its definition?
-
Given the following class block, will every object of this class have a unique copy of the
centerMaxCap
attribute/variable or will every object share a singular and realtime value of the centerMaxCap
field/variable?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private static int centerMaxCap;
private int attendCount;
public static void gCenterCap(int cap) {
OOPConceptsinJava.centerMaxCap = cap;
}
public void gCountByIncrement() {
this.attendCount++;
}
public double mAttendancePercent() {
double localVar = (double) this.attendCount / (double) OOPConceptsinJava.centerMaxCap;
return localVar * 100;
}
}
-
Given the following class block, will every object of this class have a unique copy of the
attendCount
attribute/variable or will every object share a singular and realtime value of the attendCount
field/variable?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title OOP Concepts in Java.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class OOPConceptsinJava {
private static int centerMaxCap;
private int attendCount;
public static void gCenterCap(int cap) {
OOPConceptsinJava.centerMaxCap = cap;
}
public void gCountByIncrement() {
this.attendCount++;
}
public double mAttendancePercent() {
double localVar = (double) this.attendCount / (double) OOPConceptsinJava.centerMaxCap;
return localVar * 100;
}
}
- TRUE or FALSE: Every object is an exact copy of its respective class block?
- TRUE or FALSE: A Recursive method (or function) can never result in an infinite repetition or recurrence?
- TRUE or FALSE: With regard to OOP in Java, the the DEFAULT Constructor is responsible for initializing all the static-based attributes of a class?
- TRUE or FALSE: With respect to Object-Oriented Programming in Java, the the DEFAULT Constructor is responsible for initializing all the instance-based attributes of a class?