Java as an Object-Oriented Program language really allows us to do is to create classes to inherit commonly used states and behavior (fields and methods) from other classes.
Base Class: The class whose features are inherited is known as a base class(or a super class or a parent class).
Extended class The class that inherits the other class is known as an extended class(a derived class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Base Class
sample/People.java
package sample;
public class People {
private String name;
private int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
public String move() {
return this.name + " is moving";
}
/**
* @return String return the name
*/
public String getName() {
return name;
}
/**
* @return int return the age
*/
public int getAge() {
return age;
}
}
- Created people constructor with name and age parameters.
Extended class
sample/American.java
package sample;
public class American extends People {
private String language;
private String conutry;
public American(String name, int age, String language, String conutry) {
super(name, age);
this.language = language;
this.conutry = conutry;
}
public String speak() {
return this.getName() + " can speak " + this.language;
}
@Override
public String move() {
return this.getName() + " is moving in "+ this.conutry;
}
/**
* @return String return the language
*/
public String getLanguage() {
return language;
}
/**
* @return String return the conutry
*/
public String getConutry() {
return conutry;
}
}
- speak() method is a unique method for American Class
- with extends keywords American class can access People class’s methods and fields.
Main Class
sample/Main.java
package sample;
public class Main {
public static void main(String[] args) {
People tim = new People("Tim", 45);
American mike = new American("Mike", 23, "English", "conutry");
// From Base Class
System.out.println(mike.getName());
System.out.println(mike.getAge());
System.out.println(mike.move());
// From American Class
System.out.println(mike.getLanguage());
System.out.println(mike.getConutry());
System.out.println(mike.speak());
}
}
Mike
23
Mike is moving in conutry
English
conutry
Mike can speak English
This means American class can use Methods and fields in People class which is base class by extends keyword.
@Override annotation
@Override
public String move() {
return this.getName() + " is moving in "+ this.conutry;
}
@Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override
fails to correctly override a method in one of its superclasses, the compiler generates an error.