logo codesdope

Subclass in Java


Until now, you have learned about class and objects. In this chapter, you will expand your knowledge to an advanced level. But before that, let's learn modifiers.

Modifiers


We had used public and private modifiers in previous sections.
public - It allows our method or data members to be accessed from anywhere, from the same class or different class.
private - Any data member or method which is private can be accessed only from its class. Accessing it from a different class will give you an error. Try this and see the error.

class Car{
private void print(){
  System.out.println("This is private method.");
}
}
class Bike extends Car{
public void printb(){
  System.out.println("This is public method.");
}
}
class Su0{
public static void main(String[] args){
Bike b1 = new Bike();
b1.print();
}
}
Output
Main.java:14: error: cannot find symbol
b1.print();
^
symbol: method print()
location: variable b1 of type Bike
1 error


protected - It only allows methods or data members to be accessed from its class and subclasses. We will see it when we will go through the subclass section.


You are already introduced with inheritance in OOP chapter. So, let's make a subclass of a superclass.

class Student{
  private String name;
  public String getName(){
    return name;
  }
  public void setName(String n){
    name = n;
  }
  public void printAbout(){
    System.out.println("I am a student.");
  }
}

class Undergraduate extends Student{
  public void printAbout(){
    System.out.println("I am an undergraduate.");
  }
}

class Su1{
  public static void main(String[] args){
    Student s = new Student();
    Undergraduate u = new Undergraduate();
    s.printAbout();
    u.printAbout();
  }
}
Output
I am a student.
I am an undergraduate.

There is no need to explain anything in 'Student' class.
Undergraduate extends Student
'Undergraduate' is the name of a class which is the subclass or derived class of the 'Student' class.
extends - 'extends' is used to make a subclass. Here, it means that 'Undergraduate' is extending the 'Student' class or is a subclass of the 'Student' class.
Both classes have the methods with the same name - 'printAbout'. But the definition (or statements) of methods is different. These type of methods are called polymorphic methods.
Execution of 'printAbout' from 's' ( object of 'Student' class ) will print "I am a Student." while from 'u' ( object of 'Undergraduate' class )will print "I am an Undergraduate."

We can also write:

Student a= new Undergraduate();

When a variable is declared to be of some class, it can be an instance of any of its subclass.
So, 'a' here is declared as an object of the 'Student' class but made an instance of its subclass 'Undergraduate'.

Note that the reverse is not true. We can't make a variable of a subclass as an instance of its superclass.
Undergraduate b = new Student(); is invalid.

We don't have main class in this example ( no class has the main method ). So, you can only compile it. To run it, add the main method.

Now try this example:

class Student{
  private String name;
  public String getName(){
    return name;
  }
  public void setName(String n){
    name = n;
  }
  public void printAbout(){
    System.out.println("I am a student.");
  }
}

class Undergraduate extends Student{
  public void printAbout(){
    System.out.println("I am an undergraduate.");
}
  public void printName(){
    System.out.println(name);
  }
}

class Su2{
  public static void main(String[] args){
    Student s = new Undergraduate();
    s.setName("xyz");
    s.printName();
  }
}
Output
a.java:19: error: name has private access in Student
System.out.println(name);
^
a.java:27: error: cannot find symbol
s.printName();
^
symbol: method printName()
location: variable s of type Student
2 errors

Yes, I know that the above code is giving you error. It is because 's' is declared as an object of class 'Student' and made as instance of its subclass 'Undergraduate'. It means that you can't access the methods which are only defined in the subclass if your object is not made by that subclass.

An object of a subclass can access the methods of its superclass ( if not private ) but an object of a superclass can't access the methods of its subclasses.

Here is an example showing the same.

class a{
  public static void main(String[] args){

    c1 s = new c1();
    s.m1();
    c2 a = new c2();
    a.m1();/* 'a' an object of c2 can access m1( protected method of c1(superclass) )*/
/*s.m2()*//*Remove this from comment and you will get an error because 's' an object of superclass can't access method 'm2' of subclass*/
  }
}

class c1{
  public c1(){}
  protected void m1(){

  }
}

class c2 extends c1{
  public c2(){}
  public void m2(){
    m1();//child object is able to acess protected method of parent class.( But it wouldn't be able if it was private ).
  }

}
Output

To make the method 'printName' accessible, there are two ways:
1. We make an 's' object of the class 'Undergraduate' -

Undergraduate s = new Undergraduate();

2.Typecasting - We can typecast the object 's' at any line of our code to the 'Undergraduate' class. -

((Undergraduate)s).printName();

There are many new concepts in this chapter. You need to solve questions to have a good control over them.

Subclass with constructor


class Student{
  protected String name;
  protected boolean married;
  public Student(){
    name = "unknown";
  }
  public void setMarried(boolean a){
    married = a;
  }
}
class Undergraduate extends Student{
  public Undergraduate(){
    super();
  }
}
class Postgraduate extends Student{
  public Postgraduate(){
    super();
    married = false;
  }
}
Output

Here, 'Undergraduate' and 'Postgraduate' are two subclasses of 'Student' class. Student class has a constructor. In the constructor of its subclass 'Undergraduate', super() is written. super is a reserved word in Java and Java adds 'super()' by default in the subclass constructor if we have not written it.
super() calls the class's superclass constructor. We can also pass arguments to 'super' if superclass's constructor has arguments. We will see this in the next example.
You can understand this as when we make any object of a subclass, 'super' is used to initialize its superclass first. One more thing to note here is that 'super' must be called before any statements as done in the 'Undergraduate' class.

This would have given an error:
married = False;
super();

One more example

class Rectangle{
  protected int length;
  protected int breath;
  public Rectangle(int l,int b){
    length = l;
    breath = b;
  }
  public int getArea(){
    return length*breath;
  }
  public int getPerimeter(){
    return 2*(length+breath);
  }
}
class Square extends Rectangle{
  public Square(int a){
  super(a,a);
  }
}
class Sub{
  public static void main(String[] args){
    Square s = new Square(2);
    int ar, p;
    ar = s.getArea();
    p = s.getPerimeter();
    System.out.println("Area is " + ar);
    System.out.println("Perimeter is " + p);
  }
}
Output
Area is 4
Perimeter is 8

We know that square is also a rectangle with the same length and breath. That is what we did in the constructor of 'Square'.

We created an object 's' of the class 'Square' and passed 2 at the time of creating it. So this 2 will be passed to the constructor of the class Square. Hence, the value of 'a' will be 2.

In the constructor of the class Square, we are calling the constructor of its superclass 'Rectangle' using super. Values of both length and breadth become equal to 'a' i.e. 2.

Finally, in the main class, we used the object 's' of the class Sqaure to call two methods of its parent class Rectangle - getArea and getPerimeter

super() is added in each class constructor automatically by the compiler.

Consider the following example.

class Rectangle{
  public Rectangle(){
    System.out.println("This is constructor of parent class.");
  }
}
class Square extends Rectangle{
  public Square(){
    System.out.println("This is constructor of child class.");
  }
  public void run(){
    System.out.println("This is method of child class.");
  }
}
class Sub{
  public static void main(String[] args){
    Square s = new Square();
    s.run();
}
}
Output
This is constructor of parent class.
This is constructor of child class.
This is method of child class.

Compiler automatically adds super(); at the beginning of the constructor of each class. So, here 'super();' is added by default at the beginning of the constructor of the class Square as follows.

public Square(){
super();
System.out.println("This is constructor of child class.");
}

For any class, first its constructor is called when its object is made and in the constructor, 'super();' is added at the very beginning automatically.

instanceof


instanceof operator is used to check if an object is an instance of a class or not. It returns true if a given object is an instance of the class, else it returns false. The example given below will make it clear.

class Rectangle{
  public Rectangle(){
    
  }
}
class Square extends Rectangle{
  public Square(){
	  super();
  }
}
class Sub{
  public static void main(String[] args){
    Square a = new Square();
    Rectangle b = new Rectangle();
    Rectangle c = new Square();
    System.out.println(a instanceof Square);
    System.out.println(b instanceof Square);
    System.out.println(c instanceof Square);
    System.out.println(a instanceof Rectangle);
    System.out.println(b instanceof Rectangle);
    System.out.println(c instanceof Rectangle);
  }
}
Output
true
false
true
true
true
true

In theory, there is no big difference between theory and practice. But in practice, there is.
-Yogi Berra


Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.