Practice ProgramsInheritance1
Practice ProgramsInheritance1
package J1;
// Access the method and variable from the Vehicle (Parent) class
car.showSpeed(); // Inherited from Vehicle class
// Access the method and variable from the Car (Child) class
car.displayCarInfo(); // Defined in Car class
}
}
Hierarchial Inheritance
//Parent class (Vehicle)
class Vehicle1 {
// Variable in Vehicle class
int speed;
// Car-specific method
void displayModel() {
System.out.println("This is a car.");
}
}
// Bike-specific method
void displayType() {
System.out.println("This is a bike.");
}
}
Upcasting:
package J1;
//Parent class (Animal)
class Animal1 {
// Method to be overridden
void makeSound() {
System.out.println("The animal makes a sound.");
}
}
class Parent {
void display() {
System.out.println("Parent class method");
}
}
class Parent {
int value = 10;
}
void display() {
System.out.println("Child class value: " + value);
System.out.println("Parent class value: " + super.value); // Accesses Parent class variable
}
}
class Parent {
int age;
In Java, the protected access specifier (or access modifier) is one of the four visibility
modifiers, along with private, public, and default (no modifier). It determines the scope
within which a class member (like a variable, method, or constructor) can be accessed.
Members marked with protected can be accessed by any class within the same package as the
class in which they are declared. This is similar to the default (package-private) access modifier.
Access by Subclasses (Even in Different Packages):
The main distinction between protected and default access is that protected members can also
be accessed by subclasses, even if they are in a different package.
This allows subclasses to inherit and use these members, promoting reusability and extending
class functionality while still keeping those members somewhat restricted.
Cannot Be Accessed by Non-Subclass Classes in Different Packages:
A class in another package cannot access the protected member unless it is through inheritance
(i.e., the class is a subclass of the class with the protected member).
class Parent {
protected String name = "ParentName";