Ch3 Objects Classes
Ch3 Objects Classes
Java Classes
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
Ex. student.java
Create a class named "student" with a variable x:
class student
{
int rno=101;
String name=”Tanay”;
}
Create an Object
In Java, an object is created from a class. We have already created the class
named student, so now we can use this to create objects.
To create an object of student, specify the class name, followed by the object
name, and use the keyword new:
Example
Create an object called "s1" and print the value of rno and name:
String name=”Tanay”;
public static void main(String[] args) {
student s1 = new student(); // s1 is an object of class student
System.out.println(s1.rno); //101
System.out.println(s1.name); //Tanay
}}
Multiple Objects
String name=”Tanay”;
}}
Java Programming Page 2
Bhagwan Mahavir University
3.2 Memory allocation for object / How are Java objects stored in memory?
This is different from C++ where objects can be allocated memory either on Stack
or on Heap.
In C++, when we allocate the object using new(), the object is allocated on Heap,
otherwise on Stack if not global or static.
In Java, when we only declare a variable of a class type, only a reference is created
(memory is not allocated for the object).
For example, following program fails in the compilation. Compiler gives error
“Error here because t is not initialized”.
class Test {
// class contents
void show()
System.out.println("Test::show() called");
Test t;
}}
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
Test t = new Test(); // all objects are dynamically allocated
t.show(); // No error
}
}
Method in Java
It also provides the easy modification and readability of code, just by adding or
removing a chunk of code.
Method Declaration
It has six components that are known as method header, as we have shown in the
following figure.
Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier
in our application.
Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must be
subtraction(). A method is invoked by its name.
Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
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.
In Java, Method Overloading is not possible by changing the return type of the
method only.
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
Example:
class Adder{
int add(int a,int b){
return a+b;
}
class addition{
public static void main(String[] args){
Adder a1=new Adder();
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
In this example, we have created two methods that differs in data type.
The first add method receives two integer arguments and second add method
receives two double arguments.
class Adder{
int add(int a, int b){
return a+b;
}
double add(double a, double b){
return a+b;
} }
class TestOverloading2{
public static void main(String[] args){
Adder a1=new Adder();
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Java Programming Page 11
Bhagwan Mahavir University
Output:
22
24.9
In java, method overloading is not possible by changing the return type of the
method only because of ambiguity. Let's see how ambiguity may occur:
class Adder
{
int add(int a,int b)
{
return a+b;
}
Output:
Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives string array
as arguments only.
class TestOverloading4{
public static void main(String[] args)
{
System.out.println("main with String[]");
}
public static void main(String args)
{
System.out.println("main with String");
}
public static void main()
{
System.out.println("main without args");
} }
Constructors in Java
At the time of calling constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
<class_name>()
{
//Statements
}
class Addition
{
Addition() //creating a default constructor
{
System.out.println("Addition is created");
}
public static void main(String args[]){
Addition a1=new Addition();//calling a default constructor
}
}
Output:
Addition is created.
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n) {
id = i;
name = n;
}
Java Programming Page 16
Bhagwan Mahavir University
Output:
111 Karan
222 Aryan
Copy Constructor
Example:
class student
int id;
String name;
id=i;
name=n;
id=s.id;
name=s.name;
void display() {
System.out.println(id+" "+name);
s1.display();
s2.display();
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and
their types.
class student {
int id;
String name;
id=i;
name=n;
student(student s) {
id=s.id;
name=s.name;
void display() {
System.out.println(id+" "+name);
s1.display();
s2.display();
}}
There are many differences between constructors and methods. They are given
below.
A constructor is used to initialize the state A method is used to expose the behavior
of an object. of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.
The constructor name must be same as the The method name may or may not be
class name. same as the class name.
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs(Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your current class
also.
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Example:
import java.util.*;
class student{
int sid;
String sname;
void getdata() {
System.out.println("Enter SId:");
sid=sc.nextInt();
System.out.println("Enter Sname:");
sname=sc.next();
void putdata() {
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
}}
int tid;
String tname;
void get() {
System.out.println("Enter TId:");
Java Programming Page 23
Bhagwan Mahavir University
tid=sc.nextInt();
System.out.println("Enter Tname:");
tname=sc.next();
void put() {
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname);
}}
class inheritance{
t1.getdata(); t1.put();
t1.get(); }}
t1.putdata();
Example:
import java.util.*;
class student
int sid;
String sname;
void getdata()
System.out.println("Enter SId:");
sid=sc.nextInt();
System.out.println("Enter Sname:");
sname=sc.next();
void putdata()
System.out.println("========================");
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
int tid;
String tname;
void get() {
System.out.println("Enter TId:");
tid=sc.nextInt();
Java Programming Page 25
Bhagwan Mahavir University
System.out.println("Enter Tname:");
tname=sc.next();
void put() {
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname);
}}
int pid;
String pname;
void getp() {
System.out.println("Enter PId:");
pid=sc.nextInt();
System.out.println("Enter Pname:");
pname=sc.next();
void putp() {
System.out.println("PId is:"+pid);
System.out.println("Pname is:"+pname);
System.out.println("========================");
}}
Java Programming Page 26
Bhagwan Mahavir University
class multilevel{
p1.getdata();
p1.get();
p1.getp();
p1.putdata();
p1.put();
p1.putp();
}}
Example:
import java.util.*;
class student{
int sid;
String sname;
void getdata() {
System.out.println("Enter SId:");
sid=sc.nextInt();
System.out.println("Enter Sname:");
sname=sc.next();
void putdata() {
System.out.println("========================");
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
}}
int tid;
String tname;
void get() {
System.out.println("Enter TId:");
tid=sc.nextInt();
System.out.println("Enter Tname:");
tname=sc.next();
void put() {
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname); }}
Java Programming Page 28
Bhagwan Mahavir University
int pid;
String pname;
void getp() {
System.out.println("Enter PId:");
pid=sc.nextInt();
System.out.println("Enter Pname:");
pname=sc.next(); }
void putp() {
System.out.println("PId is:"+pid);
System.out.println("Pname is:"+pname);
System.out.println("========================");
}}
class hirarchical{
public static
p1.getdata();
p1.getp();
p1.putdata();
p1.putp();
Java Programming Page 29
Bhagwan Mahavir University
t1.getdata();
t1.getp();
t1.putdata();
t1.putp(); }}
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
We can use super keyword to access the data member or field of parent(super)
class.
Example:
import java.util.*;
class student
{
int sid;
String sname;
void getdata()
{
sname="BMU";
}
void putdata()
{
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
}}
The super keyword can also be used to invoke the parent class constructor.
Example:
class student{
int sid;
String sname;
student() {
sid=101;
sname="BMU";
void putdata() {
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
}}
int tid;
String tname;
teacher() {
tid=201;
tname="DKP"; }
void put() {
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname); }}
class super2{
t1.putdata();
t1.put(); }
The super keyword can also be used to invoke parent class method.
Example:
class student
int sid;
String sname;
student() {
sid=101;
sname="BMU";
void putdata() {
System.out.println("SId is:"+sid);
System.out.println("Sname is:"+sname);
int tid;
String tname;
teacher() {
tid=201;
tname="DKP";
void put() {
System.out.println("TId is:"+tid);
System.out.println("Tname is:"+tname);
}}
class super3{
t1.put(); }
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example:
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
void show()
{
super.show(); // call parent class show()
System.out.println("Child's show()");
}}
class Main {
public static void main(String[] args)
{
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
Example:
class student
int rno;
String name,grade;
this.rno=rno;
this.name=name;
this.grade=grade;
void putdata() {
System.out.println("Roll No:"+rno);
System.out.println("Name:"+name);
System.out.println("Grade:"+grade);
}}
class this_ex1{
s1.getdata(101,"DKP","A+");
s1.putdata();
}}
Java Programming Page 39
Bhagwan Mahavir University
You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example
Example:
class student{
int rno;
String name,grade;
void greeting() {
System.out.println("Hello, Guys Welcome to Java World");
}
void getdata(int rno,String name,String grade) {
this.rno=rno;
this.name=name;
this.grade=grade;
}
void putdata() {
this.greeting();
System.out.println("Roll No:"+rno);
System.out.println("Name:"+name);
System.out.println("Grade:"+grade);
}}
class this_ex2{
public static void main(String s[]) {
student s1=new student();
s1.getdata(101,"DKP","A+");
s1.putdata();
}}
The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
class student{
student(){
student(int x)
System.out.println(x);
}}
class this_ex3{
}}
The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual use
of this keyword.
Example:
class Student {
int rollno;
String name,grade;
float fee;
Java Programming Page 42
Bhagwan Mahavir University
Sr.
Key This super
No.
Interaction
this keyword used to call default super keyword used to call default
2 with class
constructor of the same class. constructor of the parent class.
constructor
We can apply static keyword with variables , methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.
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.
The static variable gets memory only once in the class area at the time of
class loading.
class Counter
{
int count=0; //will get memory each time when the instance is created
Counter()
{
count++; //incrementing value
System.out.println(count);
}
Output:
1
1
1
As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
class Counter
{
static int count=0; //will get memory each time when the instance is created
Counter()
{
count++; //incrementing value
System.out.println(count);
}
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
class Student
{
int r;
String name;
static String college = "GTU";
static void change() //static method {
college = "BMU";
}
Student(int r, String name)
{
this.r = r;
this.name = name; }
void display()
{
System.out.println(r+" "+name+" "+college);
}
}
public class static_ex
{
public static void main(String args[])
{
System.out.println(Student.college);
Student.change();
Student s1 = new Student(111,"Tanay");
s1.display();
}
}
Output:
GTU
111 Tanay BMU
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Java Programming Page 47
Bhagwan Mahavir University
class demo{
static
{
System.out.println("static_1 block is invoked");
}
static
{
System.out.println("static _2 block is invoked");
System.out.println("Hello main");
}}
Output:
static_1 block is invoked
static_2 block is invoked
Hello main
(4) Java Static Class
We can declare a class static by using the static keyword. A class can be declared static
only if it is a nested class. It does not require any reference of the outer class. The
property of the static class is that it does not allows us to access the non-static members
of the outer class.
To understand the concept of static class first we need to understand the concept of inner,
outer, and nested class.
Inner class
The classes that are non-static and nested are called inner classes
Outer Class
Nested Class
Java allows us to define a class within a class that is known as a nested class.
It may be static or non-static. The major difference between static and non-static class is
that:
An instance of the static nested class can be created without creating an instance of
its outer class.
The static and non-static members of an outer class can be accessed by an inner
class.
The static members of the outer class can be accessed only by the static class.
Example:
class student {
System.out.println(name);
name="Tanay"; } }}
class static_class
s1.show();
System.out.println(student.name);
} }
It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.
Points to Remember
Example:
void result() {
System.out.println("It's My result");
}}
class abstract_ex{
s1.result();
} }
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.
Example:
int basic,da;
this.basic=basic;
this.da=da; }
void greetings() {
int hra;
super(basic,da);
this.hra=hra;
void ComputeSalary() {
System.out.println("Gross Salary:"+(basic+da+hra));
}}
class abstract_ex1{
sal.greetings();
sal.ComputeSalary();
}}
Output:
Gross Salary:28500
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Declaring an interface
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must implement
all the methods declared in the interface.
Syntax:
interface interface_name
{
// declare constant fields
// declare methods that abstract
// by default.
}
Relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Example
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class Interface_ex
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
}
class C implements A
{
public void display()
{
System.out.println("Hello C");
}
}
class MB
{
public static void main(String args[]){
B obj1 = new B();
obj1.display();
C obj2 = new C();
obj2.display();
}}
Example:
interface A
void greeting1();
void greeting2();
class B implements A
}}
class MB{
obj1.greeting1();
obj1.greeting2();
}}
Example:
interface A{
void display();
}
interface B{
void show();
}
class MB{
public static void main(String args[]){
C obj = new C();
obj.display();
obj.show(); }}
Output:
Hello
Welcome
Java Programming Page 58
Bhagwan Mahavir University
Interface inheritance
A class implements an interface, but one interface extends another interface.
Example:
interface A
{
void display();
}
interface B extends A //one interface extends another interface
{
void show();
}
class C implements B // one class implements another interface
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class MB
{
public static void main(String args[])
{
C obj = new C(); obj.display(); obj.show();
}}
Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
(1) Abstract class can have abstract and non-
Interface can have only abstract methods.
abstract methods.
(2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
(3) Abstract class can have final, non-final, static
Interface has only static and final variables.
and non-static variables.
(4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
(5) The abstract keyword is used to declare
The interface keyword is used to declare interface.
abstract class.
(6) An abstract class can extend another Java class
An interface can extend another Java interface only.
and implement multiple Java interfaces.
(7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
(8) A Java abstract class can have class members
Members of a Java interface are public by default.
like private, protected, etc.
(9) Example: Example:
public abstract class student public interface A
{ {
public abstract void result(); void display();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
compile-time polymorphism
runtime polymorphism.
If you overload a static method in Java, it is the example of compile time polymorphism.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
class A{}
A a=new B();//upcasting
Example:
class student
{
void result()
{
System.out.println("Result from student class");
}
}
class poly_ex
{
public static void main(String s[])
{
student s1;
Girl g1=new Girl();
Boy b1=new Boy();
s1=g1;
s1.result();
s1=b1;
s1.result();
}
}
Output:
Result from Girl class
Result from Boy class
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all
the members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Example:
class result { {
private double per=82.61; public static void main(String args[])
class student { {
void marksheet() result r1=new result();
{ result.student s1=r1.new student();
System.out.println("Percentage is "+per); s1.marksheet();
} }} } }
class inner_class
Java Programming Page 63