An object is any entity that has a state and behavior
A class is a blueprint for the object. Before we create an object, we first need to define the class.
Create a class in Java
classClassName {// fields// methods}
fields are used to store data
methods are used to perform some operation
To create an object for bicycle we need to make class first (blueprint)
classBicycle {// state or fieldprivateint gear =5;// behavior or methodpublicvoidbraking() {System.out.println("Working of Braking"); }}
Creating an Object in Java
//Basic SchemaclassName object =newclassName();// For Bicycle Class we can create object with thisBicycle sportsBicycle =newBicycle();Bicycle touringBicycle =newBicycle();
Fields and methods of a class are also called members of the class.
Access Members of a Class
classBicycle {// field of classint gear =5;// method of classvoidbraking() {... }}// create objectBicycle sportsBicycle =newBicycle();// access field and methodsportsBicycle.gear;sportsBicycle.braking();
Create objects inside the same class
classLamp {boolean isOn;voidturnOn() { isOn =true;System.out.println("Light on? "+ isOn); }publicstaticvoidmain(String[] args) { // create an object of LampLamp led =newLamp();// access method using objectled.turnOn(); }}
publicclassMain {// method definedprivatestaticintgetSquare(int x){return x * x; }publicstaticvoidmain(String[] args) {for (int i =1; i <=5; i++) {// method callint result =getSquare(i);System.out.println("Square of "+ i +" is: "+ result); } }}-------------------//outputSquare of 1 is:1Square of 2 is:4Square of 3 is:9Square of 4 is:16Square of 5 is:25
Method overloading?
Suppose, you have to perform the addition of given numbers but there can be any number of arguments (let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int, int) for two and three parameters respectively. However, other programmers, as well as you in the future may get confused as the behavior of both methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the argument passed, one of the overloaded methods is called. This helps to increase the readability of the program
Overloading by changing the number of parameters
classMethodOverloading {privatestaticvoiddisplay(int a){System.out.println("Arguments: "+ a); }privatestaticvoiddisplay(int a,int b){System.out.println("Arguments: "+ a +" and "+ b); }publicstaticvoidmain(String[] args) {display(1);display(1,4); }}----------------// outputArguments:1Arguments:1 and 4
Method Overloading by changing the data type of parameters
A constructor in Java is similar to a method that is invoked when an object of the class is created.
In Java, a constructor is a special method with the same name as the class, invoked when an object is created. It lacks a return type and is used for initializing object attributes. Constructors can be categorized into three types:
No-Arg Constructor: Takes no parameters. If declared private, it can only be accessed within the class.
Parameterized Constructor: Accepts one or more parameters, allowing for the initialization of object attributes based on provided values.
Default Constructor: Created automatically by the compiler if no constructors are defined. Initializes instance variables with default values.
Constructors can be overloaded, allowing for multiple constructors with different parameter sets. Overloaded constructors are called based on the arguments provided during object creation.
classMain {String language;// constructor with no parameterMain() {this.language="Java"; }// constructor with a single parameterMain(String language) {this.language= language; }publicvoidgetName() {System.out.println("Programming Langauage: "+this.language); }publicstaticvoidmain(String[] args) {// call constructor with no parameterMain obj1 =newMain();// call constructor with a single parameterMain obj2 =newMain("Python");obj1.getName();obj2.getName(); }}------------------------// Output: Programming Language:JavaProgramming Language:Python
Java Access Modifiers
Access modifiers in Java control the visibility or accessibility of classes, interfaces, variables, methods, constructors, data members, and setter methods. There are four types of access modifiers in Java:
Default (Package-Private) Access Modifier:
Declarations are visible only within the same package.
No explicit keyword is used; it's the default if no modifier is specified.
Example:
packagedefaultPackage;classLogger {voidmessage(){System.out.println("This is a message"); }}
Private Access Modifier:
Declarations are visible only within the class.
Example:
classData {privateString name;// Getter methodpublicStringgetName() {returnthis.name; }// Setter methodpublicvoidsetName(String name) {this.name= name; }}publicclassMain {publicstaticvoidmain(String[] main){Data d =newData();d.setName("Programiz");System.out.println(d.getName()); // Output: The name is Programiz }}
Protected Access Modifier:
Declarations are visible within the same package or subclasses.
Example:
classAnimal {protectedvoiddisplay() {System.out.println("I am an animal"); }}classDogextendsAnimal {publicstaticvoidmain(String[] args) {Dog dog =newDog();dog.display(); // Output: I am an animal }}
Public Access Modifier:
Declarations are visible everywhere.
Example:
// Animal.java file// Public classpublicclassAnimal {// Public variablepublicint legCount;// Public methodpublicvoiddisplay() {System.out.println("I am an animal.");System.out.println("I have "+ legCount +" legs."); }}// Main.javapublicclassMain {publicstaticvoidmain(String[] args) {Animal animal =newAnimal();animal.legCount=4;animal.display(); // Output: I am an animal. I have 4 legs. }}
These access modifiers help in encapsulation, allowing control over which parts of a program can access the members of a class, preventing misuse of data.
Access Modifiers Summarized in one figure
Java Recursion
Definition:
A method calling itself is termed a recursive method, and the overall process is known as recursion.
How Recursion works?
Example:
javaCopy codeclass Factorial {staticintfactorial(int n) {if (n !=0)return n *factorial(n-1);elsereturn1; }publicstaticvoidmain(String[] args) {int number =4, result; result =factorial(number);System.out.println(number +" factorial = "+ result); }}
How it Works:
A function calls itself (recursive call).
Termination condition is crucial to avoid infinite recursion.
Advantages:
Simplicity: Recursive solutions are often simpler and easier to understand.
Quick Implementation: Less time-consuming to write, debug, and maintain.
Disadvantages:
Memory Usage: Recursion uses more memory as each call allocates new storage on the stack.
Speed: Generally slower compared to iterative solutions.
Recommendation:
Choose recursion for simplicity and ease of understanding.
Consider alternatives for performance-critical applications
Java instanceof Operator:
Definition:
Checks whether an object is an instance of a particular class or interface.
Syntax:
objectName instanceof className;
Example:
classMain {publicstaticvoidmain(String[] args) {String name ="Programiz";boolean result1 = name instanceof String;System.out.println("name is an instance of String: "+ result1);Main obj =newMain();boolean result2 = obj instanceof Main;System.out.println("obj is an instance of Main: "+ result2); }}
Output:
name is an instance of String: true
obj is an instance of Main: true