Sec-88
  • πŸ§‘Whoami
  • πŸ•ΈοΈWeb-AppSec
    • Features Abuse
      • 2FA
      • Ban Feature
      • CAPTCHA
      • Commenting
      • Contact us
      • File-Upload
      • Inviting Feature
      • Messaging Features
      • Money-Related Features
      • Newsletter
      • Profile - Settings
      • Registration
      • Reset Password
      • Review
      • Rich Editor/Text
      • Social Sharing
      • Billing-Shipping Address Management
      • Integrations - Webhooks
      • API Key Management
    • Reconnaissance
      • Attacking Organizations with big scopes
    • Subdomain Enumeration
    • Fingerprinting
    • Dorking
    • XSS-HTML Injection
    • Improper Authentication
      • JWT Security
    • OAUTH Misconfigurations
      • OAuth 2.0 Basics
      • OAUTH Misconfigurations
    • Auth0 Misconfigurations
    • Broken Access Control
      • Insecure Direct Object References (IDOR)
      • 403 Bypass
    • Broken Link Injection
    • Command Injection
    • CORS
    • CRLF
    • CSRF
    • Host Header Attacks
    • HTTP request smuggling
    • JSON Request Testing
    • LFI
      • LFI to RCE
    • No Rate Limit
    • Parameters Manual Testing
    • Open Redirect
    • Registration & Takeover Bugs
    • Remote Code Execution (RCE)
    • Session Fixation
    • SQL Injection
      • SQL To RCE
    • SSRF
    • SSTI
    • Subdomain Takeover
    • Web Caching Vulnerabilities
    • WebSockets
    • XXE
      • XXE to RCE
    • Cookie Based Attacks
    • CMS
      • AEM [Adobe CMS]
    • XSSI (Cross Site Script Inclusion)
    • NoSQL injection
    • Local VS Remote Session Fixation
    • Protection
      • Security Mechanisms for Websites
      • Cookie Flags
      • SameSite Cookie Restrictions
      • Same-origin policy (SOP)
      • CSP
    • Hacking IIS Applications
    • Dependency Confusion
    • Attacking Secondary Context
    • Hacking Web Sockets
    • IDN Homograph Attack
    • DNS Rebinding Attack
    • LLM Hacking Checklist
    • Bypass URL Filtration
    • Cross-Site Path Traversal (CSPT)
    • PostMessage Security
    • Prototype Pollution
      • Client-Side Prototype Pollution
      • Server-Side prototype pollution
    • Tools-Extensions-Bookmarks
    • WAF Bypassing Techniques
    • SSL/TLS Certificate Lifecycle
    • Serialization in .NET
    • Client-Side Attacks
      • JavaScript Analysis
    • Bug Bounty Platforms/Programs
  • βœ‰οΈAPI-Sec
    • GraphQL API Security Testing
      • The Basics
      • GraphQL Communication
      • Setting Up a Vulnerable GraphQL Server
      • GraphQL Hacking Tools
      • GraphQL Attack Surface
      • RECONNAISSANCE
      • GraphQL DOS
      • Information Disclosure
      • AUTHENTICATION AND AUTHORIZATION BYPASSES
      • Injection Vulnerabilities in GraphQL
      • REQUEST FORGERY AND HIJACKING
      • VULNERABILITIES, REPORTS AND EXPLOITS
      • GraphQL Hacking Checklist
    • API Recon
    • API Token Attacks
    • Broken Object Level Authorization (BOLA)
    • Broken Authentication
    • Evasive Maneuvers
    • Improper Assets Management
    • Mass Assignment Attacks
    • SSRF
    • Injection Vulnerabilities
    • Excessive Data Exposure
    • OWASP API TOP 10 MindMap
    • Scanning APIs with OWASP ZAP
  • πŸ“±Android-AppSec
    • Setup Android App Pentesting environment on Arch
    • Setup Android App Pentesting environment on Mac M4
    • Setup Android Pentesting Environment on Debian Linux
    • Android App Fundamentals
      • Android Architecture
      • Android Security Model
      • Android App Components
        • Intents
        • Pending Intents
    • Android App Components Security Cheatsheet
    • Android App Pentesting Checklist
    • How To Get APK file for application
    • ADB Commands
    • APK structure
    • Android Permissions
    • Exported Activity Hacking
    • BroadcastReceiver Hacking
    • Content Provider Hacking
    • Signing the APK
    • Reverse Engineering APK
    • Deep Links Hacking
    • Drozer Cheat Sheet
    • SMALI
      • SMALI Cheat Sheet
      • Smali Code Patching Guide
    • Intent Redirection Vulnerability
    • Janus Vulnerability (CVE-2017-13156)
    • Task Hijacking
    • Hacking Labs
      • Injured Android
      • Hacking the VulnWebView Lab
      • Hacking InsecureBankv2 App
    • Frida Cheat Sheet
  • πŸ“ΆNetwork-Sec
    • Networking Fundamentals
    • Open Ports Security Testing
    • Vulnerability Scanning
    • Client Side Attacks
    • Port Redirection and Tunneling
    • Password Attacks
    • Privilege Escalation [PrevEsc]
      • Linux Privilege Escalation
    • Buffer Overflow (BOF)
      • VulnServer
      • Sync Breez Enterprize
      • Crashed CTF
      • BOF for Linux
    • AV Evasion
    • Post Exploitation
      • File Transfer
      • Maintaining Access
      • Pivoting
      • Clean Up
    • Active Directory
      • Basic AD Pentesting
  • πŸ’»Desktop AppSec
    • Thin Client vs. Thick Client
  • ☁️Cloud Sec
    • Salesforce Hacking
      • Basics
      • Salesforce SAAS Apps Hacking
    • Firebase
    • S3 Buckets Misconfigurations
  • πŸ‘¨β€πŸ’»Programming
    • HTML
    • JavaScript (JS)
      • window.location object
    • Python
      • Python Tips
      • Set
        • SetMethods
    • JAVA
      • Java Essentials
      • Java Essentials Code Notes
      • Java OOP1
      • JAVA OOP Principles
        • Inheritance
        • Method Overriding
        • Abstract Class
        • Interface
        • polymorphism
        • Encapsulation
        • Composition
      • Java OOP Challenges
      • Exception Handling
    • Go
      • Go Syntax Tutorial in one file
      • Methods and Interfaces
      • Go Slices
      • Go Maps
      • Go Functions
      • Concurrency
      • Read Files
      • Write Files
      • Package
        • How to make personal Package
        • regexp Packages
        • Json
        • bufio
        • Time
      • Signals-Exit
      • Unit Testing
  • πŸ–₯️Operating Systems
    • Linux
      • Linux Commands
      • Tools
      • Linux File System
      • Bash Scripting guide
      • tmux
      • Git
      • Install Go tools from private repositories using GitHub PAT
    • VPS
    • Burp Suite
  • ✍️Write-Ups
    • Hunting Methodology
    • API BAC leads to PII Data Disclosure
    • Misconfigured OATUH leads to Pre-Account Takeover
    • Automating Bug Bounty with GitHub Actions
    • From Recon to Reward: My Bug Bounty Methodology when Hunting on Public Bug Bounty Programs
    • Exploring Subdomains: From Enumeration to Takeover Victory
    • 0-Click Account Takeover via Insecure Password Reset Feature
    • How a Simple Click Can Lead to Account Takeover: An OAuth Insecure Implementation Vulnerability
    • The Power Of IDOR even if it is unpredictable IDs
    • Unlocking the Weak Spot: Exploiting Insecure Password Reset Tokens
    • AI Under Siege: Discovering and Exploiting Vulnerabilities
    • Inside the Classroom: How We Hacked Our Way Past Authorization on a Leading EdTech Platform
    • How We Secured Our Client’s Platform Against Interaction-Free Account Thefts
    • Unchecked Privileges: The Hidden Risk of Role Escalation in Collaborative Platforms
    • Decoding Server Behavior: The Key to Mass Account Takeover
    • Exploiting JSON-Based CSRF: The Hidden Threat in Profile Management
    • How We Turned a Medium XSS into a High Bounty by Bypassing HttpOnly Cookie
Powered by GitBook
On this page
  • Java Class and Objects
  • Create a class in Java
  • Method overloading?
  • Java Constructors
  • Java Access Modifiers
  • Access Modifiers Summarized in one figure
  • Java Recursion
  • Java instanceof Operator:

Was this helpful?

Edit on GitHub
  1. Programming
  2. JAVA

Java OOP1

(Class, Object, Constructor, Overloading, Java Access Modifiers, Recursion, Instanceof Operator)

Java Class and Objects

  • 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

class ClassName {
  // 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)

class Bicycle {
  // state or field
  private int gear = 5;
  // behavior or method
  public void braking() {
    System.out.println("Working of Braking");
  }
}
  • Creating an Object in Java

//Basic Schema
className object = new className();
// For Bicycle Class we can create object with this
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();
  • Fields and methods of a class are also called members of the class.

  • Access Members of a Class

class Bicycle {
  // field of class
  int gear = 5;
  // method of class
  void braking() {
    ...
  }
}

// create object
Bicycle sportsBicycle = new Bicycle();
// access field and method
sportsBicycle.gear;
sportsBicycle.braking();
  • Create objects inside the same class

class Lamp {
  boolean isOn;
  void turnOn() {
    isOn = true;
    System.out.println("Light on? " + isOn);

  }

  public static void main(String[] args) {    
    // create an object of Lamp
    Lamp led = new Lamp();
    // access method using object
    led.turnOn();
  }
}
  • Declaring a Java Method

returnType methodName() {
  // method body
}
-------------------------
modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
  // method body
}
// calls the method
addNumbers();
  • Java Method for Code Re-usability

public class Main {
  // method defined
  private static int getSquare(int x){
    return x * x;
  }

  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {

      // method call
      int result = getSquare(i);
      System.out.println("Square of " + i + " is: " + result);
    }
  }
}

-------------------
//output
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square 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

class MethodOverloading {
    private static void display(int a){
        System.out.println("Arguments: " + a);
    }
    private static void display(int a, int b){
        System.out.println("Arguments: " + a + " and " + b);
    }
    public static void main(String[] args) {
        display(1);
        display(1, 4);
    }
}
----------------
// output
Arguments: 1
Arguments: 1 and 4
  • Method Overloading by changing the data type of parameters

class MethodOverloading {
    // this method accepts int
    private static void display(int a){
        System.out.println("Got Integer data.");
    }
    // this method  accepts String object
    private static void display(String a){
        System.out.println("Got String object.");
    }

    public static void main(String[] args) {
        display(1);
        display("Hello");
    }
}
-----------------------------
// Output:
Got Integer data.
Got String object.

Java Constructors

  • 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:

    1. No-Arg Constructor: Takes no parameters. If declared private, it can only be accessed within the class.

    2. Parameterized Constructor: Accepts one or more parameters, allowing for the initialization of object attributes based on provided values.

    3. 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.

    class Main {
    
      String language;
    
      // constructor with no parameter
      Main() {
        this.language = "Java";
      }
    
      // constructor with a single parameter
      Main(String language) {
        this.language = language;
      }
    
      public void getName() {
        System.out.println("Programming Langauage: " + this.language);
      }
    
      public static void main(String[] args) {
    
        // call constructor with no parameter
        Main obj1 = new Main();
    
        // call constructor with a single parameter
        Main obj2 = new Main("Python");
    
        obj1.getName();
        obj2.getName();
      }
    }
    ------------------------
    // Output: 
    Programming Language: Java
    Programming 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:

  1. 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:

      package defaultPackage;
      class Logger {
          void message(){
              System.out.println("This is a message");
          }
      }
  2. Private Access Modifier:

    • Declarations are visible only within the class.

    • Example:

      class Data {
          private String name;
      
          // Getter method
          public String getName() {
              return this.name;
          }
      
          // Setter method
          public void setName(String name) {
              this.name = name;
          }
      }
      
      public class Main {
          public static void main(String[] main){
              Data d = new Data();
              d.setName("Programiz");
              System.out.println(d.getName()); // Output: The name is Programiz
          }
      }
  3. Protected Access Modifier:

    • Declarations are visible within the same package or subclasses.

    • Example:

      class Animal {
          protected void display() {
              System.out.println("I am an animal");
          }
      }
      
      class Dog extends Animal {
          public static void main(String[] args) {
              Dog dog = new Dog();
              dog.display(); // Output: I am an animal
          }
      }
  4. Public Access Modifier:

    • Declarations are visible everywhere.

    • Example:

      // Animal.java file
      // Public class
      public class Animal {
          // Public variable
          public int legCount;
      
          // Public method
          public void display() {
              System.out.println("I am an animal.");
              System.out.println("I have " + legCount + " legs.");
          }
      }
      
      // Main.java
      public class Main {
          public static void main(String[] args) {
              Animal animal = new Animal();
              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 {
        static int factorial(int n) {
            if (n != 0)
                return n * factorial(n-1);
            else
                return 1;
        }
    
        public static void main(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:

    class Main {
        public static void main(String[] args) {
            String name = "Programiz";
            boolean result1 = name instanceof String;
            System.out.println("name is an instance of String: " + result1);
    
            Main obj = new Main();
            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
  • Inheritance Example:

    class Animal {}
    
    class Dog extends Animal {}
    
    class Main {
        public static void main(String[] args) {
            Dog d1 = new Dog();
            System.out.println(d1 instanceof Dog);      // true
            System.out.println(d1 instanceof Animal);   // true
        }
    }
  • Interface Example:

    interface Animal {}
    
    class Dog implements Animal {}
    
    class Main {
        public static void main(String[] args) {
            Dog d1 = new Dog();
            System.out.println(d1 instanceof Animal);  // true
        }
    }
  • Note:

    • Used to check if an object is an instance of a specific class or interface.

    • Can be used in inheritance scenarios to check superclass or interface instances.

    • Returns true if the object is an instance; otherwise, returns false.

    • All classes in Java are inherited from the Object class.

PreviousJava Essentials Code NotesNextJAVA OOP Principles

Last updated 1 year ago

Was this helpful?

Accessibility of all Access Modifiers in Java
Working of Java Recursion
πŸ‘¨β€πŸ’»
Accessibility of all Access Modifiers in Java
A function is calling itself