Lecture 3
Lecture 3
In the example below, we created a static method, which means that it can be accessed without creating an object
of the class, unlike public, which can only be accessed by objects:
● final: The “final” is the keyword that can be used for immutability and restrictions
in variables, methods, and classes.
● finally: The “finally block” is used in exception handling to ensure that a certain
piece of code is always executed whether an exception occurs or not.
● finalize: finalize is a method of the object class, used for cleanup before garbage
collection.
Strings
In Java, String is the type of objects that can store the sequence of characters enclosed by
double quotes and every character is stored in 16 bits.
Java provides a robust and flexible API for handling strings, allowing for various
operations such as concatenation, comparison, and manipulation.
A String Array in Java is an array that stores string values. The string is nothing but an
object representing a sequence of char values.
However, if the same method is present in both the superclass and subclass, what will happen?
In this case, the method in the subclass overrides the method in the superclass. This concept is known as method
overriding in Java.
// method in the superclass System.out.println("I eat dog public static void main(String[]
food"); args) {// create an object of the
public void eat() { subclass
}
System.out.println("I can eat"); Dog labrador = new Dog();
// new method in subclass
}} // call the eat() method
public void bark() {
// Dog inherits Animal labrador.eat();
System.out.println("I can bark");
class Dog extends Animal { labrador.bark();
}}
// overriding the eat() method }
}
super Keyword in Java Inheritance
we saw that the same method in the subclass overrides the method in superclass.
In such a situation, the super keyword is used to call the method of the parent class from the method of the child
class.
We can also use the super keyword to call the constructor of the superclass from the constructor of the subclass.
small.display();
protected Members in Inheritance
In Java, if a class includes protected fields and methods, then these fields and methods are accessible from the
subclass of the class.
class Main {
class Animal {
public static void main(String[] args) {
protected String name;
// create an object of the subclass
protected void display() {
Dog labrador = new Dog();
System.out.println("I am an animal.");
// access protected field and method
}
// using the object of subclass
}
labrador.name = "Rocky";
class Dog extends Animal {
labrador.display();
public void getInfo() {
labrador.getInfo();
System.out.println("My name is " + name);
}
}}
}
● The most important use of inheritance in Java is code reusability. The code that is
present in the parent class can be directly used by the child class.