kothapelli.ranadheer@gmail.com

Java inheritance with example

Inheritance is a mechanism in Java that allows one class to inherit the properties and behaviors of another class. The class that inherits is called the child or subclass, and the class that is inherited from is called the parent or superclass.

Here’s an example to illustrate inheritance in Java:

public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }
}

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy");
        dog.eat(); // output: Buddy is eating.
        dog.bark(); // output: Woof!
    }
}

In this example, we have defined an Animal class with a constructor that takes a name parameter and an eat method. We have also defined a Dog class that extends Animal and has a bark method.

The Dog class inherits the name and eat properties from the Animal class, and adds the bark behavior. When we create a Dog object, we can call both the inherited eat method and the bark method.

Inheritance in Java provides several benefits, including code reuse, the ability to create specialized classes from existing ones, and polymorphism. By using inheritance, we can create a hierarchy of classes that represent the real-world relationships between objects.

this keyword in java

In Java, the this keyword is a reference to the current object. It can be used to refer to instance variables and methods of the current object, or to call the current object’s constructor.

Here are some examples of how the this keyword can be used:

  1. Referring to instance variables:
public class Person {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        System.out.println(person.getName()); // output: John
    }
}

In this example, we have defined a Person class with a private instance variable called name. We have also defined a setName method that sets the value of the name variable, and a getName method that returns the value of the name variable. Inside the methods, we use the this keyword to refer to the current object’s name variable.

  1. Calling another constructor of the same class:
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name) {
        this(name, 0);
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 25);
        Person person2 = new Person("Mary");

        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 25
        System.out.println(person2.getName()); // output: Mary
        System.out.println(person2.getAge()); // output: 0
    }
}

In this example, we have defined a Person class with two constructors. The first constructor takes two parameters, name and age, and sets the corresponding instance variables. The second constructor takes only one parameter, name, and calls the first constructor with age set to 0. Inside the constructor call, we use the this keyword to refer to the current object.

In summary, the this keyword in Java is a reference to the current object. It can be used to refer to instance variables and methods of the current object, or to call the current object’s constructor.

static keyword in java

In Java, the static keyword is used to create variables and methods that are associated with a class rather than with individual objects of the class. This means that static variables and methods can be accessed without creating an object of the class, using the class name instead.

Here’s an example of a static variable:

public class Person {
    private String name;
    private static int count = 0;

    public Person(String name) {
        this.name = name;
        count++;
    }

    public String getName() {
        return name;
    }

    public static int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John");
        Person person2 = new Person("Mary");
        Person person3 = new Person("Bob");

        System.out.println(Person.getCount()); // output: 3
    }
}

In this example, we have defined a Person class with a static variable called count, which keeps track of the number of Person objects that have been created. We have also defined a static method called getCount, which returns the value of the count variable.

In the Person constructor, we increment the count variable every time a new Person object is created. In the Main class, we create three Person objects and then use the getCount method to retrieve the value of the count variable.

static methods can also be used to perform operations that are not specific to individual objects of the class. Here’s an example:

public class MathUtils {
    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        int result = MathUtils.factorial(5);
        System.out.println(result); // output: 120
    }
}

In this example, we have defined a MathUtils class with a static method called factorial, which calculates the factorial of a given integer. We can call this method using the class name and the dot operator, without creating an object of the MathUtils class.

In summary, the static keyword is used in Java to create variables and methods that are associated with a class rather than with individual objects of the class. static variables and methods can be accessed using the class name instead of an object reference.

constructor in java

In Java, a constructor is a special method that is used to create objects of a class. It has the same name as the class and no return type. When an object of a class is created, the constructor is automatically called to initialize the object.

Here’s an example of a simple constructor in Java:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 30
    }
}

In this example, we have defined a Person class with a constructor that takes two parameters (name and age) and initializes the instance variables with those values. We can then create an object of the Person class by calling the constructor with the desired values. In this case, we create a new Person object called person1 with the name “John” and age 30.

Constructors can also be overloaded, meaning that a class can have multiple constructors with different parameter lists. Here’s an example:

public class Person {
    private String name;
    private int age;

    public Person() {
        name = "Unknown";
        age = 0;
    }

    public Person(String name) {
        this.name = name;
        age = 0;
    }

    public Person(int age) {
        name = "Unknown";
        this.age = age;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person("John");
        Person person3 = new Person(30);
        Person person4 = new Person("John", 30);

        System.out.println(person1.getName()); // output: Unknown
        System.out.println(person1.getAge()); // output: 0

        System.out.println(person2.getName()); // output: John
        System.out.println(person2.getAge()); // output: 0

        System.out.println(person3.getName()); // output: Unknown
        System.out.println(person3.getAge()); // output: 30

        System.out.println(person4.getName()); // output: John
        System.out.println(person4.getAge()); // output: 30
    }
}

In this example, we have defined four different constructors for the Person class, each with a different parameter list. We can then create objects of the Person class using any of these constructors, depending on the values we want to initialize the object with.

Methods in java

In Java, a method is a block of code that performs a specific task. It can take input in the form of parameters, and it can return output in the form of a return value. Methods are defined inside a class, and they are used to perform specific operations on objects of that class.

Here’s an example of a simple method in Java:

public class Calculator {
    public static int add(int num1, int num2) {
        int result = num1 + num2;
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        int sum = Calculator.add(3, 4);
        System.out.println(sum); // output: 7
    }
}

In this example, we have defined a Calculator class with a static method called add(). This method takes two integer parameters (num1 and num2), adds them together, and returns the result as an integer. We can then call this method in our Main class by using the syntax ClassName.methodName(), passing in the two integer values we want to add.

Java also supports non-static methods, which can be called on an instance of a class rather than on the class itself. Here’s an example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println("Hello, my name is " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        person1.sayHello(); // output: Hello, my name is John
    }
}

In this example, we have defined a Person class with a non-static method called sayHello(). This method simply prints out a message that includes the person’s name. We can then call this method on an instance of the Person class by using the syntax objectName.methodName(). In this case, we create a new Person object called person1 and call its sayHello() method.

What is object in java

In Java, an object is an instance of a class. A class is a blueprint or template for creating objects, and an object is a specific instance of that blueprint.

Objects in Java have state and behavior. The state of an object is represented by its attributes, also known as fields or instance variables. The behavior of an object is represented by its methods, which define the actions that can be performed on the object.

Here’s an example of an object in Java:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 30

        person1.setAge(31);
        System.out.println(person1.getAge()); // output: 31
    }
}

In this example, we have defined a Person class with fields for name and age, and methods for getting and setting those fields. We then create a new Person object called person1 and set its name and age fields. We can then use the getName() and getAge() methods to get the values of these fields, and the setAge() method to update the age field.

What is class in java

In Java, a class is a blueprint or template for creating objects. It defines a set of attributes and methods that are common to all objects of a certain type.

A class contains fields, which represent the attributes or data of an object, and methods, which define the behavior of the object. For example, a Person class might have fields like name, age, and gender, and methods like getName(), getAge(), setAge(), etc.

When you create an object of a class, you are creating an instance of that class. You can then use the methods and fields of the object to perform operations and store data.

Here is an example of a simple class in Java:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

In this example, we have defined a Person class with fields for name and age, and methods for getting and setting those fields. We have also defined a constructor method that sets the initial values for the fields when a new Person object is created.

Why java is object oriented programing language?

Java is an object-oriented programming language because it is designed around the concept of objects. Object-oriented programming (OOP) is a programming paradigm that focuses on creating objects that contain both data and behavior, and using these objects to build complex programs.

In Java, everything is an object. The language is designed to support the four fundamental principles of OOP: encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation means that the internal workings of an object are hidden from the outside world, and can only be accessed through a public interface. In Java, this is achieved through the use of access modifiers like public, private, and protected, which control the visibility of a class’s fields and methods.

Inheritance allows classes to inherit the properties and behavior of other classes. This allows for code reuse and can help to simplify complex programs. In Java, inheritance is implemented using the extends keyword.

Polymorphism means that objects of different types can be used interchangeably, as long as they implement the same interface or inherit from the same parent class. This allows for more flexible and modular code. In Java, polymorphism is achieved through the use of interfaces and inheritance.

Abstraction means that complex systems can be simplified by hiding unnecessary details and exposing only the most important features. In Java, this is often done through the use of abstract classes and interfaces.

Overall, Java’s support for these fundamental principles of OOP makes it a powerful and flexible programming language that is well-suited for building complex software systems.

Naming convention in java

Naming conventions in Java are important for writing readable and maintainable code. Here are some commonly used naming conventions in Java:

  1. Packages: Package names should be all lowercase and use a domain name as the prefix, in reverse order. For example, com.example.projectname.
  2. Classes: Class names should be nouns and use mixed case with the first letter of each internal word capitalized. For example, MyClass.
  3. Interfaces: Interface names should be adjectives or nouns and use mixed case with the first letter of each internal word capitalized. For example, Runnable.
  4. Methods: Method names should be verbs and use mixed case with the first letter of the first word lowercase and the first letter of each internal word capitalized. For example, calculateTotal.
  5. Variables: Variable names should be nouns and use mixed case with the first letter of each internal word capitalized. For example, firstName.
  6. Constants: Constant names should be all uppercase and use underscore to separate words. For example, MAX_VALUE.
  7. Packages, classes, and interfaces: Packages, classes, and interfaces should use meaningful names that describe their purpose.
  8. Methods and variables: Methods and variables should use meaningful names that describe their purpose.

By following these naming conventions, your code will be more readable and maintainable. It’s also important to be consistent with your naming conventions throughout your code.

control statements in java

Control statements in Java are used to control the flow of execution in a program. There are three main types of control statements in Java: selection statements, iteration statements, and jump statements.

  1. Selection Statements: These statements are used to select one or more statements to execute based on a condition.
  • if-else statement: This statement is used to execute one block of statements if a condition is true and another block of statements if the condition is false.
if (condition) {
    // statements to execute if condition is true
} else {
    // statements to execute if condition is false
}
  • switch statement: This statement is used to select one of several blocks of statements to execute based on the value of an expression.
switch (expression) {
    case value1:
        // statements to execute if expression equals value1
        break;
    case value2:
        // statements to execute if expression equals value2
        break;
    ...
    default:
        // statements to execute if none of the above cases are true
        break;
}
  1. Iteration Statements: These statements are used to repeat one or more statements multiple times.
  • for loop: This statement is used to execute a block of statements a fixed number of times.
for (initialization; condition; update) {
    // statements to execute
}
  • while loop: This statement is used to execute a block of statements as long as a condition is true.
while (condition) {
    // statements to execute
}
  • do-while loop: This statement is used to execute a block of statements at least once, and then repeat the block of statements as long as a condition is true.
do {
    // statements to execute
} while (condition);
  1. Jump Statements: These statements are used to transfer control to another part of the program.
  • break statement: This statement is used to terminate a loop or switch statement.
break;
  • continue statement: This statement is used to skip the current iteration of a loop and continue to the next iteration.
continue;
  • return statement: This statement is used to exit a method and return a value to the calling method.
return value;

These are the control statements in Java. As a programmer, it’s important to understand how to use these statements to control the flow of execution in your programs.