OOPS in JAVA

Rishi Prakash
9 min readSep 22, 2023

--

Refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks assigned by you.

Class

  • user-defined data type which defines its properties and its functions.
  • It is a user-defined blueprint or prototype from which objects are created
  • Class is the only logical representation of the data.
  • The class does not occupy any memory space till the time an object is instantiated.
  • Class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.

Object

  • is a run-time entity.
  • instance of the class, created to use the attributes and methods of a class.
  • An object can represent a person, place or any other item. An object can operate on both data members and member functions.

Instance variable- variables inside an object

a reference variable is any variable that can hold reference of an object and an instance variable is a primitive or non-primitive variable that is declared within a class.

// creating object of class Test
Test t = new Test(); // new -used to allocate memory in heap
// Test() -used to call constructor

When an object is created using a “new” keyword, then space is allocated for the variable (here ‘t’ ) in a heap, and the starting address is stored in the stack memory

class Pen {
String color;
String type; // ball or gel

public void printColor() {
System.out.println("The color of this Pen is " + this.color);
}
}


public class OOPS {
public static void main(String args[]) {
Pen p1 = new Pen();
p1.color = blue;
p1.type = gel;


Pen p2 = new Pen();
p2.color = black;
p2.type = ball;


Pen p3 = new Pen();
p3.color = red;
p3.type = gel;


p1.printColor();
p2.printColor();
p3.printColor();
}
}

This Keyword

  • A reference variable - refers to the current instance of the class on which the method or constructor is being invoked.
  • Used to -
  1. pass the current object as a parameter to another method
  2. refer to the current class instance variable

Adv-

  1. It helps to distinguish between instance variables and local variables with the same name.
  2. It can be used to pass the current object as an argument to another method.
  3. It can be used to return the current object from a method.
  4. It can be used to invoke a constructor from another overloaded constructor in the same class.

CONSTRUCTORS

A special method - invoked automatically at the time of object creation. It is used to initialize the data members of new objects

Generally-

  • Constructors have the same name as class or structure.
  • No return type. (Not even void)
  • Constructors are only called once, at object creation.

It is not necessary to write a constructor for a class ; because java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.

  1. Non- Parametrised Constructor-
class Student {
String name;
int age;

public void printInfo(){
System.out.println(this.name);
System.out.println(this.age);
}

Student() {
System.out.println("Constructor called");
name="Rishi";
age=20;
}
}

public class Main {
public static void main(String args[]) {
Student s1 = new Student();

s1.printInfo();
}
}

/*
output=
Constructor called
Rishi
20
*/

2. Parametrised Constructor-

class Student {
String name;
int age;

public void printInfo() {
s.o.pln(this.name);
s.o.pln(this.age);
}

Student(String NAME, int AGE) {
this.name=NAME;
this.age=AGE;
}
}

public class OOPS {
public static void main(String args[]) {
Student s1 = new Student("Rishi", 20);
s1.printInfo();
}

/*
output-
Rishi
20
*/

3. Copy Constructor

class Student {
String name;
int age;

public void printInfo() {
s.o.pln(this.name);
s.o.pln(this.age);
}

Student(){
}

Student(Student s2) {
this.name=s2.name;
this.age=s2.age;
}
}

public class OOPS {
public static void main(String args[]) {
Student s1 = new Student();
s1.name = "Rishi";
s1.age = 20;

Student s2 = new Student(s1);
s2.printInfo();
} // we have never assigned values to s2, copied from s1

/*
output-
Rishi
20
*/

4 Pillers of OOPS

1.Polymorphism

Polymorphism is the ability to present the same interface for differing underlying forms (data types).

With polymorphism, each of these classes will have different underlying data.

Types of Polymorphism

  1. Compile Time Polymorphism (Static)
  2. Runtime Polymorphism (Dynamic)

Compile Time Polymorphism : The polymorphism which is implemented at the compile time is known as compile-time polymorphism.

If it generates error then it is generated at Compile time only.( thats why preferred over Run time error)

Example — Method Overloading

  • Method Overloading : Method overloading is a technique which allows you to have more than one function with the same function name but with different functionality. Method overloading can be possible on the following basis:

1. The type of the parameters passed to the function.

2. The number of parameters passed to the function.

3. By changing the data type.

class Student {
String name;
int age;
int roll;

public void displayInfo(String name) {
System.out.println(name);
}


public void displayInfo(int age) {
System.out.println(age);
}

public void displayInfo(int age, int roll) {
System.out.println(age);
System.out.println(roll);
}


public void displayInfo(String name, int age) {
System.out.println(name);
System.out.println(age);
}

` public void displayInfo() {
System.out.println(this.name);
System.out.println(this.age);
}
}


public class Main {
public static void main(String args[]) {
Student s1 = new Student();
s1.name = "Rishi";
s1.age = 20;

s1.displayInfo("rishi");
s1.displayInfo();
}
}

Run time polymorphism — later

2.Inheritance

Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically.

You can reuse, extend or modify the attributes and behaviors which are defined in other classes.

keyword: Extends

— Base class / parent class/ superclass

— Derived/ extended/ child class

Types of inheritance:

Single inheritance : When one class inherits another class, it is known as single level inheritance

class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}

Hierarchical inheritance : Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}
class Circle extends Shape {
public void area(int r) {
System.out.println((3.14)*r*r);
}

Multilevel inheritance : Multilevel inheritance is a process of deriving a class from another derived class.

class Shape {
public void area() {
System.out.println("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
System.out.println((1/2)*b*h);
}
}
class EquilateralTriangle extends Triangle {
int side;
public void area(int side) {
System.out.println((1/2)*side*side);
}

Hybrid inheritance : Hybrid inheritance is a combination ofsimple, multiple inheritance and hierarchical inheritance.

Multiple Inheritance not allowed in java

Packages in java

Package is a group of similar types of classes, interfaces and sub-packages. Packages can be built-in or user defined.

“import” keyword used

Built-in packages — java, util, io etc.

public static void main()- while public?

during execution in java run time environment needs to find in which class main fn is present, so need to be public

Access modifiers in JAVA

  • Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
  • Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  • Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
  • Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
package newpackage;


class Account {
public String name;
protected String email;
private String password;


public void setPassword(String password) {
this.password = password;
}
}
public class Sample {
public static void main(String args[]) {
Account a1 = new Account();
a1.name = "Apna College";
a1.setPassword("abcd");
a1.email = "hello@apnacollege.com";
}
}

3.Encapsulation

Encapsulation is the process of combining data and functions into a single unit called class.

In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class.

In simpler words, attributes of the class are kept private and public getter and setter methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.(Data hiding: a language feature to restrict access to members of an object, reducing the negative effect due to dependencies. e.g. “protected”, “private” feature in Java).

Implemented using ACCESS MODIFIERS

4.Abstraction

We try to obtain an abstract view, model or structure of a real life problem, and reduce its unnecessary details. With definition of properties of problems, including the data which are affected and the operations which are identified, the model abstracted from problems can be a standard solution to this type of problems. It is an efficient way since there are nebulous real-life problems that have similar properties.

In simple terms, it is hiding the unnecessary details & showing only the essential parts/functionalities to the user.

Done using CLASSES and OBJECTS

Any class having ≥1 abstract method, must be declared as abstract

why obj of abstract class cant be created?

Suppose we create an object of an abstract class , and using it we call another abstract function defined inside the class, it will create error coz that fn will not have any body to execute that fn.

Abstraction is achieved in 2 ways :

  • Abstract class
  • Interfaces (Pure Abstraction)
  1. Abstract Class
  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.
abstract class Animal {
abstract void walk();
void breathe() {
System.out.println("This animal breathes air");
}
Animal() {
System.out.println("You are about to create an Animal.");
}
}


class Horse extends Animal {
Horse() {
System.out.println("Wow, you have created a Horse!");
}
void walk() {
System.out.println("Horse walks on 4 legs");
}
}


class Chicken extends Animal {
Chicken() {
System.out.println("Wow, you have created a Chicken!");
}
void walk() {
System.out.println("Chicken walks on 2 legs");
}
}


public class OOPS {
public static void main(String args[]) {
Horse horse = new Horse();
/*
You are about to create an Animal
Wow, you have created a Horse!
*/
horse.walk();
horse.breathe();
}
}

2. Interfaces

  • All the fields in interfaces are public, static and final by default.
  • All methods are public & abstract by default.
  • A class that implements an interface must implement all the methods declared in the interface.
  • Interfaces support the functionality of multiple inheritance.
interface Animal {
public void walk(); // also written as void walk() only
/*void eats(){
s.o.pln("This animal eats"); //ERROR-- interface methods can't have body
}
*/
}

interface Herbivore{

}

class Horse implements Animal, Herbivore { //multiple inheritance obtained thru Interface
public void walk() {
System.out.println("Horse walks on 4 legs");
}
}


class Chicken implements Animal {
public void walk() {
System.out.println("Chicken walks on 2 legs");
}
}


public class OOPS {
public static void main(String args[]) {
Horse horse = new Horse();
horse.walk();
}
}

--

--

Rishi Prakash
Rishi Prakash

No responses yet