Mastering Java Fundamentals: From Scratch to Advanced

Access Modifier

whenever we are writing own class we have provide same information about our file to JVM like –

  1. that class is accessible any where or not
  2. child class creation is possible or not
  3. object creation is possible or not we can specific this information using appropriate modifier.

the only applicable modifier for top class are:-

public
default
final
abstract
strictfp

Inner class applicable modifier are:-

public
default
final
abstract
strictfp
private
protected
static

1. Public Modifier

  • if a class declare as public then we can access that class anywhere.

Error

  • if class Demo1 is not public then while compile Demo2 class will get compile time error (pack1.Demo1 is not in pack1 : cannot be accessed outside package)
package pack1;

class Demo1 {
    public void m1() {
        System.out.println("Hello");
    }
}
package pack2;

class Demo2 {
    public static void main() {
        Demo1 d = new Demo1();
        d.m1();
    }
}

Without Error

package pack1;

public class Demo1 { // Changed to public
    public void m1() {
        System.out.println("Hello");
    }
}
package pack2;

import pack1.Demo1; // Importing Demo1

public class Demo2 {
    public static void main(String[] args) { // Corrected main method signature
        Demo1 d = new Demo1();
        d.m1();
    }
}

2. Default Modifier

if a class declare default then we access the class only current package. that it outside package we cannot access.(it also known as package level access)

class Demo1 {
    public void m1() {
        System.out.println("Hello Ankit");
    }
}
class Demo2 {
    public static void main(String[] args) {
        Demo1 d = new Demo1();
        d.m1();
    }
}

3. Final Modifier

final is a modifier applicable for class ,variable and method.

Final Method :

  • whatever method parent has by default available to the child using inheritance if the child not satisfied parent method implementation then child is allowed redefine the method based on there requirement this process is called overriding.
  • if parent class method declare as final we not override the method in child class.

Error

class Animal {
    final void sound() {
        System.out.println("This animal makes a sound.");
    }
}
public class Main extends Animal {
    void sound() {
        System.out.println("The dog barks.");
    }
    public static void main(String[] args) {
        Main obj = new Main();
        obj.sound();
    }
}

The compilation error occurs because the sound() method in the Animal class is declared as final. In Java, a final method cannot be overridden by a subclass. The attempt to override sound() in Main results in an error.

we declare parent class as final so we don’t override final class in parent that’s why error occur. if we remove final keyword in parent class then error remove.

Final Class :

  • If a class declare as final we can not extends functionality of that class. that is we can not create child class of that class.
  • Inheritance not possible using final class.
Error
final class Parent {
    void show() {
        System.out.println("This is the Parent class.");
    }
}
public class Main extends Parent {
    void show() {
        System.out.println("This is the Child class.");
    }
    public static void main(String[] args) {
        Parent obj = new Parent();
        obj.show();
    }
}

The error occurs because the Parent class is declared as final. In Java, a final class cannot be inherited, meaning no other class can extend it. The attempt to extend Parent in the Main class results in a compilation error.

Note

  • every method present in final class also a final , but every variable present inside final class in not be final.
  • Final modifier is secure.
  • Disadvantage of final modifier is we can not implementation Inheritance and Polymorphism which is key concepts of OOPS.
  • If no specific requirement then not use final keyword.

3. Abstract Modifier :

  • abstract is a modifier applicable for class and method but not for variable.

Abstract Method :

  • Even thus we don’t know about implementation still we can declare a method with abstract method.
  • In abstract method declaration is available but implementation is not . it’s declaration ends with semicolon.
public abstract void m1(); ✅
public abstract void m1() ❌
  • Child class is reponsible to provide implementation to parent class abstract method.
abstract class vechile{
abstract public int requiredWheel();
}
class Bus extends vechile{
public int  requiredWheel(){
return 7;
}
}
  • By default abstract method in parent class we provided guidelines for child class. that is which method compulsory child has to implement.
  • Abstract method never talk about implementation if any modifier not talk about implementation that is from illegal combination for abstract modifiers.
final
native
synchronized
static
private
strictfp

Abstract Class :

  • For any java class if we not allow to create object(Because of partial implementation) such type of class is called abstract class.
  • Abstract class instantiation is not possible.
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
// Animal a = new Animal(); // ❌ ERROR: Cannot instantiate an abstract class
Dog dog = new Dog(); // ✅ Instantiating a concrete subclass
dog.makeSound(); // Output: Woof!
}
}
  • if a class contain atleast one abstract method that compulsory we declare class as abstract class otherwise get compile time error.

4 .Private Modifier :

  • If a member is private then we access that member only within the class , outside the class we can not access.
  • Abstract method should be available to the child class to provide implementation whereas the private method not available to the child class . Hence private abstract combination is illegal for method.

5. Protected Member :

  • If member declare as protected then we access that member any where that current package but outside the package access only child class.
  • we can access protected member within the current package anywhere using parent and child class reference.
  • But access protected member in outside package only in the child class .

Data Hiding

  • Outside person can not access our internal data directly or our internal data should not go out directly this OOPS feature is nothing but data hiding.
  • After validation outside person can access our internal data.
    • Example – After providing proper user name or password we can able to access our gmail inbox information.
  • By declaring data member (variable) as private we can achieve data hiding.
   class Student {
    private int age;  // Data Hiding: Age is private
    // Setter method to set age
    public void setAge(int age) {
        if (age > 0) { // Adding a simple validation
            this.age = age;
        } else {
            System.out.println("Age cannot be negative or zero!");
        }
    }
    // Getter method to get age
    public int getAge() {
        return age;
    }
  }
   public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.setAge(20);  // Setting age using setter method
        System.out.println("Student's Age: " + student.getAge()); // Accessing age using getter method
    }
  }
  • The main advantage of data hiding is security.
  • It is highly recommend to use declare data member as private.

Abstraction

  • Hiding internal implementation and just highlight set of service what they offering is concept of abstraction.
  • In bank ATM GUI screen bank people are highlight though set of service what they offering without highlight internal implementation.
  • The main advantage of abstraction we are achieve security because we con not highlight our internal implementation, without effecting outside person we can able to perform any type of change in our internal system Hence enhancement become easy, it improve maintainability of application.
  • By using interface and abstract class we can implement abstraction.
abstract class Vehicle {
    // Abstract method (does not have a body)
    abstract void start();
    // Concrete method
    void stop() {
        System.out.println("Vehicle is stopping...");
    }
}
class Car extends Vehicle {
    void start() {
        System.out.println("Car is starting with a key...");
    }
}
public class AbstractionExample {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        myCar.start();  
        myCar.stop();  
    }
}

Encapsulation

  • The process of binding data and corresponding method into a single unit is nothing but Encapsulation.
  • If any component follows data hidding and abstraction such type of component said to be encapsulation component.
                      [Encapsulation = Data Hiding + Abstraction]
  • The main advantage of encapsulation are achive security, enhancement become easy, maintainability of application.
  • The main advantage of encapsulation is we can achive security but disadvantage of encapsulation is it increase length of the code and slow down excution.
class Person {
    // Private variables (cannot be accessed directly outside the class)
    private String name;
    private int age;
    // Public getter method to access the private variable
    public String getName() {
        return name;
    }
    // Public setter method to modify the private variable
    public void setName(String newName) {
        name = newName;
    }
    // Public getter for age
    public int getAge() {
        return age;
    }
    // Public setter for age
    public void setAge(int newAge) {
        if (newAge > 0) { // Simple validation
            age = newAge;
        } else {
            System.out.println("Age must be positive!");
        }
    }
}
// Main class
public class EncapsulationExample {
    public static void main(String[] args) {
        Person p = new Person();
        // Setting values using setters
        p.setName("John");
        p.setAge(25);
        // Getting values using getters
        System.out.println("Name: " + p.getName());
        System.out.println("Age: " + p.getAge());
    }
}

Interface

I have defined the interface in 3 ways.

  1. Any service requirement specification it consider as an interface.
  2. From the client’s perspective, an interface defines the set of services they expect to receive. From the service provider’s perspective, an interface defines the set of services they are offering. Therefore, any agreement or contract between the client and the service provider is referred to as an interface.
    • Example -Through the bank ATM’s GUI screen, the bank showcases the set of services it offers. At the same time, the same GUI screen represents the set of services that the customer is willing to accept. Therefore, this GUI screen acts as a contract or agreement between the customer and the bank, ensuring that both parties are aligned on the services being provided and accessed. It serves as a common interface that facilitates the interaction and defines the terms of the transaction.
  3. Inside Interface every method is always abstract whether we are declare or not , Hence interface is consider as 100% pure abstract class.

Summarized definition

Any service requirement specification or any contract between client and service provider or 100% pure abstract class in nothing as Interface.

  • Whenever we implement any interface for each every method of that interface we have to provide implementation otherwise we have to declare class as abstract then next level child class responsibility to provide implementation.
  • Every interface method always public and abstract whether we declare or not , Hence we are declare interface method compulsory we should declare as public otherwise we will get compile time error.
interface MyInterface {
    void show();  
    void display();
}
abstract class MyAbstractClass implements MyInterface {  
    public void show() {  // when we implement abstract method then public modifier use
        System.out.println("Show method implemented");
    }
    // display() is not implemented, so we must declare the class as abstract.
}

class MyConcreteClass extends MyAbstractClass {
    public void display() {  // Now providing implementation for display()
        System.out.println("Display method implemented");
    }
    
    public static void main(String[] args) {
        MyConcreteClass obj = new MyConcreteClass();
        obj.show();
        obj.display();
    }
}

INHERITANCE(IS – A Relationship) :

  • Inheritance where a child class (or subclass) derives properties and behaviors (methods) from a parent class (or superclass). It helps establishing a relationship between classes.
  • The main advantage if inheritance is code reusability.
  • By using extends keyword we can implementation inheritance.
class Animal {
    void sound() {
        System.out.println("Some sound");
    }
}
// Child class inheriting from Animal
class Dog extends Animal {
    void sound() {
        System.out.println("Woof!");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();  
        dog.sound(); 
    }
}
  • Child refrence we called parent or child but the refrence we only all only parent not child.
  • Every class in java is a child class of object either directly or indirectly so that object class method available every java class.

Types Of Inheritance :

Java supports three types of inheritance:

1. Single Inheritance

A child class inherits from a single parent class.

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark();
}
}

2. Multilevel Inheritance

A child class inherits from a parent class, and another child class inherits from it (forming a chain).

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}
class Mammal extends Animal {
    void walk() {
        System.out.println("Mammals can walk.");
    }
}
class Dog extends Mammal {
    void bark() {
        System.out.println("Dog barks.");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // Inherited from Animal
        dog.walk(); // Inherited from Mammal
        dog.bark(); // Defined in Dog
    }
}

3. Hierarchical Inheritance

A single parent class has multiple child classes.

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks.");
    }
}
class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows.");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // Inherited method
        dog.bark();

        Cat cat = new Cat();
        cat.eat();  // Inherited method
        cat.meow();
    }
}

Question – why java can not support for multiple inheritance ?

Ans – A java class can not extends more the one class at a time , there may be chance of ambiguity problem hence java can not support multiple inheritance. But interface con extends any no of class at a time so interface support multiple inheritance.

Congratulations on completing this Java fundamentals tutorial! You’ve taken the first step toward mastering Java, learning its core concepts, syntax, and essential features. Keep practicing, explore advanced topics, and build real-world projects to strengthen your skills.

Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top