Java OOP Flashcards
Describe what ‘Public’ means in a user defined method
public - access modifier. It means the method can be accessed from anywhere.
Describe what ‘Static’ means in a user defined method
Static means that the method can be accessed without any objects.
Describe what ‘Void’ means in a user defined method
Void means that the method does not return any value
Describe the complete syntax of a method
modifier static returnType nameOfMethod (parameters) { // method body }
What are some advantages of using methods?
The main advantage is code reusability. We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, “write once, reuse multiple times
Methods make code more readable and easier to debug
What is a constructor?
In Java, every class has its constructor that is invoked automatically when an object of the class is created. A constructor is similar to a method but in actual, it is not a method.
What are the three types of constructors in Java?
No-Arg Constructor
Default Constructor
Parameterized Constructor
Describe a No-Arg Constructor
A Java constructor may or may not have any parameters (arguments). If a constructor does not accept any parameters, it is known as a no-arg constructor. For example,
private Constructor( ) { // body of constructor }
Describe a default constructor
If you do not create any constructors, the Java compiler will automatically create a no-argument constructor during run-time. This constructor is known as the default constructor. The default constructor initializes any uninitialized instance variables with default values
Describe parametrized constructor
Similar to methods, we can pass parameters to a constructor. Such constructors are known as a parameterized constructor. For example,
private Constructor (arg1, arg2, ..., argn) { // constructor body }
What is constructor overloading?
In constructor overloading, there are two or more constructors with different parameters
Important Notes about Constructors
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
The name of the constructor should be the same as that of class.
A Java constructor must not have a return type.
What are access modifiers?
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For example,
class Animal { public void method1() {...}
private void method2() {…}
}
There are four access modifiers keywords in Java
Default
Private
Protected
Public
What is a private access modifier
When variables and methods are declared private, they cannot be accessed outside of the class