- Can I define more than one public class in a Java package?
- Example
- Compile-time error
- Can we declare more than one class in a single Java program?
- Two Ways of Implementing Multiple Classes in a single Java Program
- How the compiler behave with Multiple non-nested classes
- Example
- Output
- How the compiler behave with Nested classes
- Example
- Output
- How to Extends Multiple Class in Java – Complete Guide 2023
- Why do We Need to Extend Multiple Classes?
- Can We Extend Multiple Classes in Java?
- Why It is Not Possible to Extend Multiple Classes in Java?
- What is Diamond Problem in Java?
- Diamond Problem Program in Java (Why We Can’t Extend multiple Classes in Java?)
- How to Extends Multiple Class in Java?
- Java Program to Implement Multiple Inheritance
- Recommended Posts
- FAQs
- Can We Extend Multiple Classes in Java?
- Is It Possible to Implement Multiple Interfaces in Java?
- Can we Extend Class and Implement Interfaces in Java?
- Extend Two Classes in Java
- Extend a Class in Java
- Extend Two Classes in Java
- Multiple classes in one file in Java
- Methods to Implement Multiple Classes In One Java Program
- 1) Nested classes
- 2) Multiple non-static nested classes
Can I define more than one public class in a Java package?
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
Example
In the following example we have two classes Student and AccessData we are having both of them in the same class and declared both public.
import java.util.Scanner; public class Student < private String name; private int age; Student()< this.name = "Rama"; this.age = 29; >Student(String name, int age) < this.name = name; this.age = age; >public void display() < System.out.println("name: "+this.name); System.out.println("age: "+this.age); >> public class AccessData < public static void main(String args[]) < //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); Student obj1 = new Student(name, age); obj1.display(); Student obj2 = new Student(); obj2.display(); >>
Compile-time error
On compiling, the above program generates the following compile-time error.
AccessData.java:2: error: class Student is public, should be declared in a file named Student.java public class Student < ^ 1 error
To resolve this either you need to shift one of the classes into a separate file or,
- Remove the public declaration before the class that doesn’t contain a public static void main(String args) method.
- Name the file with the class name that contains main method.
In this case, remove the public before the Student class. Name the file as “AccessData.java”.
Can we declare more than one class in a single Java program?
A single Java program contains two or more classes, it is possible in two ways in Java.
Two Ways of Implementing Multiple Classes in a single Java Program
How the compiler behave with Multiple non-nested classes
In the below example, the java program contains two classes, one class name is Computer and another is Laptop. Both classes have their own constructors and a method. In the main method, we can create an object of two classes and call their methods.
Example
public class Computer < Computer() < System.out.println("Constructor of Computer class."); >void computer_method() < System.out.println("Power gone! Shut down your PC soon. "); >public static void main(String[] args) < Computer c = new Computer(); Laptop l = new Laptop(); c.computer_method(); l.laptop_method(); >> class Laptop < Laptop() < System.out.println("Constructor of Laptop class."); >void laptop_method() < System.out.println("99% Battery available."); >>
When we compile the above program, two .class files will be created which are Computer.class and Laptop.class. This has the advantage that we can reuse our .class file somewhere in other projects without compiling the code again. In short, the number of .class files created will be equal to the number of classes in the code. We can create as many classes as we want but writing many classes in a single file is not recommended as it makes code difficult to read rather we can create a single file for every class.
Output
Constructor of Computer class. Constructor of Laptop class. Power gone! Shut down your PC soon. 99% Battery available.
How the compiler behave with Nested classes
Once the main class is compiled which has several inner classes, the compiler generates separate .class files for each of the inner classes.
Example
// Main class public class Main < class Test1 < // Inner class Test1 >class Test2 < // Inner class Test2 >public static void main(String [] args) < new Object() < // Anonymous inner class 1 >; new Object() < // Anonymous inner class 2 >; System.out.println("Welcome to Tutorials Point"); > >
In the above program, we have a Main class that has four inner classes Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class, it will generate the following class files.
Output
Welcome to Tutorials Point
How to Extends Multiple Class in Java – Complete Guide 2023
Extend is one of the keywords in Java which is used for inheritance and indicates that we are inheriting all the properties of the Parent class to the Child class.
The class from which we are inheriting the properties like variables and methods is called as Parent class and the class which is using those properties is called as Child class.
Why do We Need to Extend Multiple Classes?
In many situations, we may need the same properties that we have already developed in other classes. So instead of creating those properties again if we can reuse those properties of other classes, then we can save memory and as well as save our time.
Similarly in Java also we can use other class properties in our class by extending that class.
Ok, Let’s understand through an example.
Suppose, we have a mobile manufacturing company and to develop different types of mobiles, we may need different parts of it like chips, batteries, wires, and many more which are commonly used in most the mobiles. So what can we do is, we will design the same parts with basic functionalities with it and we can use them with different mobiles by modifying them as per our need.
In Java, We can develop one class with some basic functionalities which will be common to other classes and we can extend this class whenever required.
Can We Extend Multiple Classes in Java?
No, We can’t extend multiple classes in Java. As Java doesn’t support Multiple Inheritance, So we can’t extend multiple classes in Java. We can only extend one class and implement multiple Interfaces.
We can declare abstract fields in Interfaces and then we can access them in child classes by using the implement keyword in Java. In this way, we can achieve Multiple Inheritance in Java.
Why It is Not Possible to Extend Multiple Classes in Java?
It is not possible to extend multiple classes in Java because of redundancy. If Java will allow extending of multiple classes, then redundant data may arise.
Though it’s not possible to extend multiple classes. Still, let’s consider like, you have used the same method to perform( ) in two different classes Class A & Class B and you want to access that method in child class. So when you will call that method from a child class, it is not possible to differentiate between which class method you want to call actually. Mostly this problem is similar to Diamond Problem which arises in multiple inheritances.
Later we will try to find the solution for how to extends multiple classe in Java.
What is Diamond Problem in Java?
The problem in which one Class D is trying to inherit the same property from two or more than two different classes like Class B and Class C which is again inherited from one parent Class A is called as Diamond Problem in Java.
Suppose we have declared one abstract method perform( ) in abstract Class A and we have two subclasses Class B & Class C extend Class A and also implemented the abstract perform( ) method. Now Class D extends both Class B & Class C (Only, for example, not supported by Java). We have created the obj of Class D and through this obj, we are trying to access the perform( ) method. This will create an ambiguous situation because it will create confusion about which method you are calling the same method we have implemented in both Class B and Class C.
Let’s see the above problem that we have faced through programming for better knowledge so that we will get clear idea about why Java doesn’t support multiple inheritance or why we can’t extend multiple classes in Java.
Diamond Problem Program in Java (Why We Can’t Extend multiple Classes in Java?)
package codingface.java.logical; package codingface.java.logical; < public ); > >
package codingface.java.logical; < public ); > > package codingface.java.logical; public > The above class D will give syntax error as well as compile time error if you will forcefully run the above Class D.
So the above program is the live example of the Diamond Problem in Java and also we have proved that we can’t extend multiple classes in Java.
Let’s see how we can accomplish our goal like how to extends multiple class in Java.
How to Extends Multiple Class in Java?
As we have already discussed that Java doesn’t support multiple inheritance, So we can’t extend multiple classes in Java. We can accomplish our goal of Multiple Inheritance by using the Interface in Java.
Let’s see how we will resolve our query “How to extends multiple class in Java?.
We can extend one class and can implement multiple interfaces in Java which will resolve our problem of creating ambiguity also.
Java Program to Implement Multiple Inheritance
package cf.java.inheritance; < ); > >
package cf.java.inheritance; package cf.java.inheritance; package cf.java.inheritance; < @Override ); > > IPhone Conclusion
In this tutorial, We know about how to extends multiple class in Java.
Though we can’t extends multiple class in Java as Java doesn’t support multiple inheritance, but we can overcome this problem by using interfaces.
Recommended Posts
FAQs
Can We Extend Multiple Classes in Java?
No, We can’t extend multiple classes in Java. We can use interface as an alternatives to accomplish multiple inheritance.
Is It Possible to Implement Multiple Interfaces in Java?
Yes, We can implement multiple interfaces in Java.
Can we Extend Class and Implement Interfaces in Java?
Yes, We can extend one class and implement multiple interfaces simultaneously in Java.
Extend Two Classes in Java
- Extend a Class in Java
- Extend Two Classes in Java
- Extend Two Interfaces in Java
This tutorial introduces how to extend two or more classes in Java. We also included some example codes to help you understand the topic.
Inheritance is a Java OOPs feature that allows extending a class to another class to access properties of a class. Java allows extending class to any class, but it has a limit. It means a class can extend only a single class at a time. Extending more than one class will lead to code execution failure.
When a class extends a class, then it is called single inheritance . If a class extends more than one class, it is called multi-inheritance , which is not allowed in Java.
Let’s see some examples and understand the complete concept.
Extend a Class in Java
Java does not allow multiple inheritances. In this example, we created two classes. A class extends to another and executes fine; this means that Java allows the extension of a single class. Still, what if we extend two classes? We will see this in the following example below.
class Run int speed; void showSpeed() System.out.println("Current Speed : "+speed); > public class SimpleTesting extends Run public static void main(String[] args) SimpleTesting run = new SimpleTesting(); run.showSpeed(); run.speed = 20; run.showSpeed(); > > >
Current Speed : 0 Current Speed : 20
Extend Two Classes in Java
In this example method, a class extends two classes, which implies multiple inheritances. Java does not allow this process so the code does not execute and gives a compile time error. See the example below.
class Run int speed; void showSpeed() System.out.println("Current Speed : "+speed); > > class Car String color; int topSpeed; > public class SimpleTesting extends Run, Car public static void main(String[] args) SimpleTesting run = new SimpleTesting(); run.showSpeed(); run.speed = 20; run.showSpeed(); > >
Multiple classes in one file in Java
You need to have any number of classes in a single Java file, but there is a restriction that you can declare only one Java class as public modifier with the main() method and declare (without public) for the remaining classes. Moreover, we have one rule in Java that your filename must be the same as your public class name.
Methods to Implement Multiple Classes In One Java Program
1) Nested classes
A nested class is one type of inner class that accesses other instance variables of an outer class. We can use any access modifiers for the nested inner class such as private, public, protected, or default.
There are two types of nested classes defined in Java.
1. static nested class
If You define an inner class with a static keyword, such type of class is said to be a static nested class, and an inner class is also said to be a non-static nested class in Java.
Total Organization projects: 0
Inside Project class constructor.
Total Company projects: 1
Calling private method of Organization class from Project class
Greetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 10
Inside Project class constructor.
Total Company projects: 2
Calling private method of Organization class from Project classGreetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 20
Explanation of the program
In the above program, we have created outer class Organization , and inside it, we have created an inner class Project *. In the output, we have decided to directly access the methods and variables of an outer class Organization from the inner class Project .
2) Multiple non-static nested classes
The non-static nested class is a class within another class and should be accessible to members of the enclosing class (outer class). This class is also known as an inner class in Java. While an inner class exists within the outer class, you must instantiate the outer class first in order to instantiate the inner class.