Java Module2
Java Module2
Create a Class
Output:
0
null
Output:
Welcome to javaTpoint
Reference Variables and Assignment
class MyClass{
Output:
Your name is Java2blog
Reference variable can be of many types based on their scope
and accessibility. For example,
1. Static reference variable
2. Instance reference variable
3. Local reference variable
Method Declaration
The method declaration provides information about method
attributes, such as visibility, return-type, name, and arguments.
It has six components that are known as method header, as
we have shown in the following figure.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods. It is also known as the standard library
method or built-in method. We can directly use these
methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Demo.java
Output:
The maximum number is: 9
User-defined Method
The method written by the user or programmer is known as a
user-defined method. These methods are modified according
to the requirement.
1. class Addition
2. {
3. public static void main(String[] args)
4. {
5. int a = 19;
6. int b = 5;
7. //method calling
8. int c = add(a, b); //a and b are actual parameters
9. System.out.println("The sum of a and b is= " + c);
10. }
11. //user defined method
12. public static int add(int n1, int n2) //n1 and n2 are
formal parameters
13. {
14. int s;
15. s=n1+n2;
16. return s; //returning the sum
17. }
}
The sum of a and b is= 24
The sum of a and b is= 24
Output:
The sum of a and b is= 24
Returning from a Method, Returning Value
Output
On executing, this program generates the following error −
Error: Main method must return a value of type void in class Sample,
please
define the main method as:
public static void main(String[] args)
Using Parameters
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:
myMethod("ram");
myMethod("Jenny");
myMethod("deepa");
// ram aaa
// Jenny aaa
// deepa aaa
Multiple Parameters
You can have as many parameters as you like:
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
// Liam is 5
// Jenny is 8
// Anja is 31
Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:
return 5 + x;
System.out.println(myMethod(3));
// Outputs 8
Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes:
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Java allows two types of constructors namely −
No argument Constructors
Parameterized Constructors
Rules for creating Java constructor
There are two rules defined for the constructor.
1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time
of object creation.
Output:
Bike is created
Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Output:
111 Karan
222 Aryan
Garbage Collection
In java, garbage means unreferenced objects.
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
int x;
public Main(int x) {
this.x = x;
Value of x = 5
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
// Class
// Helper class
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
// Main class
public class GFG {
// MAin driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Output
ob1 == ob2: true
ob1 == ob3: false
Returning Objects
a method can return any type of data, including class types that you can
create. For example, in the following Java program, the
method incrByTen() returns an object in which the value of a is ten greater
than it is in the invoking object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
obj2 = obj1.incrByTen();
obj2 = obj2.incrByTen();
}
}
When the above Java program is compile and executed, it will produce the
following output:
Method Overloading
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
Suppose you have to perform addition of the given numbers but there can
be any number of arguments, if you write the method such as a(int,int) for
two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior
of the method because its name differs.
Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, the
derived class provides the specific implementation of the method that is
already provided by the base class or parent class. In method overriding, the
return type must be the same or co-variant (return type may vary in the same
direction as the derived class).
Example: Method Overriding
Method Overriding
Consider a scenario where Bank is a class that provides functionality to
get the rate of interest. However, the rate of interest varies according to
banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and
9% rate of interest.
Java method overriding is mostly used in Runtime Polymorphism which we will
learn in next pages.
1. //Java Program to demonstrate the real scenario of Java Method Ove
rriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10.}
11.
12.class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14.}
15. class AXIS extends Bank{
16.int getRateOfInterest(){return 9;}
17. }
18.//Test class to create objects and call the methods
19. class Test2{
20.public static void main(String args[]){
21. SBI s=new SBI();
22.ICICI i=new ICICI();
23. AXIS a=new AXIS();
24.System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfIntere
st());
26.System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28.}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Overloading Constructors
Java supports constructor overloading. In constructor
loading, we create multiple constructors with the same
name but with different parameters types or with different
no of parameters.
public class Tester {
public Tester(){
message = "Hello World!";
}
public Tester(String message){
this.message = message;
}
public String getMessage(){
return message ;
}
public void setMessage(String message){
this.message = message;
}
public static void main(String[] args) {
Tester tester = new Tester();
System.out.println(tester.getMessage());
Output
Hello World!
Welcome
Recursion
Recursion in java is a process in which a method calls itself continuously.
A method in java that calls itself is called recursive method.
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Java Recursion Example 1: Finite times
1. public class RecursionExample {
2. static int count=0;
3. static void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }
9. }
10.public static void main(String[] args) {
11. p();
12.}
13. }
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
Output:
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.
Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All
students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of
all objects. If we make it static, this field will get the memory only once.
Output:
class OuterClass {
// ...
class NestedClass {
// ...
}
}
There are two types of nested classes you can create in Java.
Recommended reading:
Java Access Modifiers
Java Static Keyword
Non-Static Nested Class (Inner Class)
Since the inner class exists within the outer class, you must instantiate the
outer class first, in order to instantiate the inner class.
Here's an example of how you can declare inner classes in Java.
double getCache(){
return 4.3;
}
}
double getClockSpeed(){
return 5.5;
}
}
}
Output:
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as
follows:
EXAMPLE:
public class Demo {
public static void Varargs(String... str) {
System.out.println("\nNumber of arguments are: " +
str.length);
System.out.println("The argument values are: ");
for (String s : str)
System.out.println(s);
}
Apple
Mango
Pear
Magic
float salary=40000;
int bonus=10000;
Output
OrderofExecution1.java
1. /* Parent Class */
2. class ParentClass
3. {
4. /* Constructor */
5. ParentClass()
6. {
7. System.out.println("ParentClass constructor executed.");
8. }
9. }
10.
11. /* Child Class */
12. class ChildClass extends ParentClass
13. {
14. /* Constructor */
15. ChildClass()
16. {
17. System.out.println("ChildClass constructor executed.");
18. }
19. }
20.
21. public class OrderofExecution1
22. {
23. /* Driver Code */
24. public static void main(String ar[])
25. {
26. /* Create instance of ChildClass */
27. System.out.println("Order of constructor execution...");
28. new ChildClass();
29. }
30. }
Output:
OrderofExecution2.java
1. class College
2. {
3. /* Constructor */
4. College()
5. {
6. System.out.println("College constructor executed");
7. }
8. }
9.
10. class Department extends College
11. {
12. /* Constructor */
13. Department()
14. {
15. System.out.println("Department constructor executed");
16. }
17. }
18.
19. class Student extends Department
20. {
21. /* Constructor */
22. Student()
23. {
24. System.out.println("Student constructor executed");
25. }
26. }
27. public class OrderofExecution2
28. {
29. /* Driver Code */
30. public static void main(String ar[])
31. {
32. /* Create instance of Student class */
33. System.out.println("Order of constructor execution in Mul
tilevel inheritance...");
34. new Student();
35. }
36. }
Output:
Example
Following java program demonstrates how to call a super class’s
constructor from the constructor of the sub class using the super
keyword.
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayPerson();
}
}
Output
Data of the Person class:
Name: Krishna
Age: 20
Example
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
Output
This is class A
This is class B
This is class C
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
final keyword
final keyword is used in different contexts. First of all, final is a non-access
modifier applicable only to a variable, a method, or a class. The following are
different contexts where final is used.
1. class Bike{
2. final int speedlimit;//blank final variable
3.
4. Bike(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike();
11. }
12.}
Output: 70
t = null;
System.out.println("end");
}
@Override protected void finalize()
{
System.out.println("finalize method called");
}
}
Output:
366712642
finalize method called
end