- Chapter 8. Classes
- Return type in Java | Example Program
- Types of Methods Declaration based on Return type in Java
- How to return primitive values like int, float, double?
- How to return class object in Java?
- How to return current or same class object in Java?
- Ways to return current/same class object
- How to return a variable in Java programming?
- Can we declare return statement inside main method in Java?
Chapter 8. Classes
A class declaration defines a new class and describes how it is implemented (§8.1).
A top level class (§7.6) is a class declared directly in a compilation unit.
A nested class is any class whose declaration occurs within the body of another class or interface declaration. A nested class may be a member class (§8.5, §9.5), a local class (§14.3), or an anonymous class (§15.9.5).
Some kinds of nested class are an inner class (§8.1.3), which is a class that can refer to enclosing class instances, local variables, and type variables.
An enum class (§8.9) is a class declared with abbreviated syntax that defines a small set of named class instances.
A record class (§8.10) is a class declared with abbreviated syntax that defines a simple aggregate of values.
This chapter discusses the common semantics of all classes. Details that are specific to particular kinds of classes are discussed in the sections dedicated to these constructs.
A class may be declared public (§8.1.1) so it can be referred to from code in any package of its module and potentially from code in other modules.
A class may be declared abstract (§8.1.1.1), and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. The degree to which a class can be extended can be controlled explicitly (§8.1.1.2): it may be declared sealed to limit its subclasses, or it may be declared final to ensure no subclasses. Each class except Object is an extension of (that is, a subclass of) a single existing class (§8.1.4) and may implement interfaces (§8.1.5).
A class may be generic (§8.1.2), that is, its declaration may introduce type variables whose bindings differ among different instances of the class.
Class declarations may be decorated with annotations (§9.7) just like any other kind of declaration.
The body of a class declares members (fields, methods, classes, and interfaces), instance and static initializers, and constructors (§8.1.7). The scope (§6.3) of a member (§8.2) is the entire body of the declaration of the class to which the member belongs. Field, method, member class, member interface, and constructor declarations may include the access modifiers public , protected , or private (§6.6). The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared member classes and member interfaces can hide member classes and member interfaces declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final (§8.3.1.2), in which case it can be assigned to only once. Any field declaration may include an initializer.
Member class declarations (§8.5) describe nested classes that are members of the surrounding class. Member classes may be static , in which case they have no access to the instance variables of the surrounding class; or they may be inner classes.
Member interface declarations (§8.5) describe nested interfaces that are members of the surrounding class.
Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.12). A class method is invoked relative to the class; an instance method is invoked with respect to some particular object that is an instance of a class. A method whose declaration does not indicate how it is implemented must be declared abstract . A method may be declared final (§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native code (§8.4.3.4). A synchronized method (§8.4.3.6) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized statement (§14.19), thus allowing its activities to be synchronized with those of other threads (§17 (Threads and Locks)).
Method names may be overloaded (§8.4.9).
Instance initializers (§8.6) are blocks of executable code that may be used to help initialize an instance when it is created (§15.9).
Static initializers (§8.7) are blocks of executable code that may be used to help initialize a class.
Constructors (§8.8) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.8.8).
Return type in Java | Example Program
Return type in Java | We know that a method is a function declared inside a class that contains a group of statements.
It is used to perform certain tasks or processing of data in the program to yield the expected results.
A method can accept data from outside and can also return the results. To return the result, a return statement is used inside a method to come out of it to the calling method.
In Java, return is a keyword that is used to exit from the method only with or without returning a value. Every method is declared with a return type in java and it is mandatory for Java methods.
Return type may be a primitive data type like int, float, double, a reference type, or void type which represents “return nothing”. i.e, they don’t give anything back.
When a method is called, the method may return a value to the caller method.
Let’s take an example program to understand the concept of java return type better.
Here, we will write a program to return the square of a number from a method. Look at the following source code.
Program source code 1:
public class Test < int square(int num)< return num * num; // return a square value. >public static void main(String[] args) < // Create an obejct of class Test. Test t = new Test(); // Call the method using object reference variable. Since the return type of this method is int, we will store it using a variable of type int. int squareOfNumber = t.square(20); // Displaying the result. System.out.println("Square of 20: " +squareOfNumber); >>
Explanation: Look at the below figure and understand the explanation that will help you to understand better.
a. In this example program, we have created a method named square(). This method accepts an integer value and calculates the square of it.
After calculating square of value, square() method returns that value to the main() method that is the calling method.
b. Inside the main() method, we are calling square() method using object reference variable t and passing 20 to it as follows: t.square(20);.
c. To get the result returned from the square() method, we have taken a variable “squareOfNumber” of type int as follows: int squareOfNumber = t.square(20);.
d. int before a method name specifies the type of value returned by the method.
e. After method name, we wrote int num as a parameter that receives an integer value into the method. We are passing a value 20 to the method at the time of calling from main method.
f. Now to calculate the square value and return it, we have used return statement (return num * num;) inside the square() method.
Thus, a return statement in java is used to return a value from a method. It can return only one value at a time. When a return statement is used inside the method, the flow of execution comes out of it and goes back to the caller method.
Types of Methods Declaration based on Return type in Java
1. Method with void type :
Here, the void represents “return nothing”. A return type void is used when there is no return value.
2. Methods with return type and value :
If a method is having int, double, float, etc other than void, we must return a value compatible with the declared return type by using the return statement.
If you are not returning any value, it will generate an error message like ” missing return statements “. Let’s take some examples related to it.
Code 2 is an invalid code because, inside the method, the return statement must be the last statement of method.
How to return primitive values like int, float, double?
Let’s take an example program where we will return primitive values like int, float, and char to methods m1(), m2(), and m3() respectively.
Program source code 2:
public class Sample < // Declare a method with return type int. int m1() < System.out.println("m1 method"); // If you declare a method to return a value, you must return a value of declared type. Since the return type of m1() method is an integer. So, we will have to return an integer value. return 20; >Similarly, float m2() < System.out.println("m2 method"); return 20.5f; >static char m3() < System.out.println("m3 method"); return 'd'; >public static void main(String[] args) < // Create an object of the class named Sample. Sample s = new Sample(); // Call m1() method using reference variable s. Since s.m1() is returning an integer value, we will store value by using a variable x with a data type int. int x = s.m1(); // Now print the return value. System.out.println("Return value of m1()= " +x); Similarly, float y = s.m2(); System.out.println("Return value of m2()= " +y); // Call static method using the class name. Since m3() method returns character, we will store a character using a variable ch with type char. char ch = Sample.m3(); System.out.println("Return value of m3() https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3954713822336382" crossorigin="anonymous" defer data-deferred="1">