Unit 3
Unit 3
Let understand the concept of Java classes and objects with an example.
Let's take an example of developing a pet management system, specially meant for
dogs. You will need various information about the dogs like different breeds of
the dogs, the age, size, etc.
You need to model real life beings, i.e., dogs into software entities.
You can see the picture of three different breeds of dogs below.
Stop here right now! List down the differences between them.
Some of the differences you might have listed out may be breed, age, size,
color, etc. If you think for a minute, these differences are also some common
characteristics shared by these dogs. These characteristics (breed, age, size,
color) can form a data members for your object.
Next, list out the common behaviors of these dogs like sleep, sit, eat, etc. So
these will be the actions for our software objects.
Class - Dogs
Data members or objects- size, age, color, breed, etc.
Methods- eat, sleep, sit and run.
2. The essence of OOP is modelling abstractions, using classes and objects. The
hard part in this endeavor is finding the right abstraction.
3.A class denotes a category of objects, and acts as a blueprint for creating
such objects.
4.A class models an abstraction by defining the properties and behaviors for the
objects representing the abstraction. An object exhibits the properties and
behaviors defined by its class.
5. The properties of an object of a class are also called attributes, and are
defined by fields in Java. A field in a class is a variable which can store a
value that represents a particular property of an object. The behaviors of an
object of a class are also known as operations, and are defined using methods in
Java.Fields and methods in a class declaration are collectively called members.
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when
looking into classes of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class, the Java compiler builds a default constructor for that
class.
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
Example
public class Puppy {
public Puppy() {
Java also supports Singleton Classes where you would be able to create only one
instance of a class.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So
basically, an object is created from a class. In Java, the new keyword is used
to create new objects.
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
If we compile and run the above program, then it will produce the following
result −
Output
Passed Name is :tommy
Example
This example explains how to access instance variables and methods of a class.
If we compile and run the above program, then it will produce the following
result −
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the
source file.
Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.
Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. We will be explaining about all these in
the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special
classes called Inner classes and Anonymous classes.
Object reference:
Assigning Object Reference Variables : Class Concept in Java Programming
1. We can assign value of reference variable to another reference variable.
2. Reference Variable is used to store the address of the variable.
3. Assigning Reference will not create distinct copies of Objects.
4. All reference variables are referring to same Object.
class RectangleDemo {
public static void main(String args[]) {
r1.length = 10;
r2.length = 20;
}
}
Output :
Typical Concept :
Suppose we have assigned null value to r2 i.e
Note : Still r2 contain reference to an object. Thus We can create have multiple
reference variables to hold single object.
Method Overloading:
Method Overloading is a feature that allows a class to have two or more methods
having same name, if their argument lists are different.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of
static binding where binding of method call to its definition happens at Compile
time.
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
In the above example – method disp() has been overloaded based on the number of
arguments – We have two definition of method disp(), one with one argument and
another with two arguments.
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
Output:
Result: Compile time error. Argument lists are exactly same. Both methods are
having same number, data types and same sequence of data types in arguments.
Case 2:
Result: Perfectly fine. Valid case for overloading. Here data types of arguments
are different.
Case 3:
Result: Perfectly fine. Valid case for overloading. Here number of arguments are
different.
Case 4:
Result: Perfectly fine. Valid case for overloading. Sequence of the data types
are different, first method is having (int, float) and second is having (float,
int).
Case 5:
Result: Compile time error. Argument lists are exactly same. Even though return
type of methods are different, it is not a valid case. Since return type of
method doesn’t matter while overloading a method.
class Demo
{
public int myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4
{
public static void main(String args[])
{
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and
argument list cannot be defined in a same class.
Question 2 – return type is different. Method name & argument list same.
class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and
argument list cannot be given in a class even though their return type is
different. Method return type doesn’t matter in case of overloading.
Output:
Bike is created
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.
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
Although Java is strictly pass by value, the precise effect differs between
whether a primitive type or a reference type is passed.
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Driver class
public class Test
{
public static void main(String args[])
{
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Output:
As we call the method equalTo, the reference ‘o’ will be assigned to the
object which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as
following statement execute.
// driver class
public class Test
{
public static void main(String args[])
{
// creating a box with all dimensions specified
Box mybox = new Box(10, 20, 15);
double vol;
Output:
Returning Objects
In java, a method can return any type of data, including objects. For example,
in the following program, the incrByTen( ) method returns an object in which the
value of a (an integer variable) is ten greater than it is in the invoking
object.
ObjectReturnDemo(int i)
{
a = i;
}
// Driver class
public class Test
{
public static void main(String args[])
{
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;
ob2 = ob1.incrByTen();
Output:
ob1.a: 2
ob2.a: 12
The various usage of keyword Java 'THIS' in Java is as per the below,
Our expected output for A and B should be initialized to the values 2 and 3
respectively.
In the method Set data, the arguments are declared as a and b, while the
instance variables are also named as a and b.
Append both 'a' and 'b' with the "this" keyword followed by a dot (.) operator.
The variables are initialized correctly, and the expected output is shown.
1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Output:
hello n
hello m
1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
Output:
hello a
10
1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Output:
5
hello a
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
Output:
1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
Output:
method is invoked
Static variable
If any variable we declared as static is known as static variable.
Static variable is used for fulfill the common requirement. For Example
company name of employees,college name of students etc. Name of the
college is common for all students.
The static variable allocate memory only once in class area at the time of
class loading.
Example
public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}
Example
class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name);
Student s2=new Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name);
}
}
Example
Output:
100
abcd
ITM
200
zyx
ITM
Example
public class A
}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we can not override final method
}
}
Example
class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}
Output
It gives an error
Example
final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}
}
Output
Output:
It gives an error
class InitializationBlock
{
int[] arrVal = new int[10];
// Initialization block
{
System.out.println("In initialization block\n");
for(int i=0; i<arrVal.length; i++)
{
arrVal[i] = (int)(100.0*Math.random());
}
}
void Display()
{
System.out.println("Start display\n");
for(int i=0; i<arrVal.length; i++)
{
System.out.println(" " + arrVal[i]);
}
System.out.println("End display\n");
}
void Display()
{
System.out.println("Start display\n");
for(int i=0; i<arrVal.length; i++)
{
System.out.println(" " + arrVal[i]);
}
System.out.println("End display\n");
}
The only difference between both the samples above is with the two static
keywords added and you can definitely see difference in the output. One outputs
different values for two objects created and other one the same values.
You can have multiple initialization blocks in a class in which case they
execute in the sequence in which they appear in the class.
Note that any initialization block present in the class is executed before the
constructor.
Access Modifier:
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors. The four access levels are −
Example
Variables and methods can be declared without any modifiers, as in the following
examples −
boolean processOrder() {
return true;
}
Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public
getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself
and hides data from the outside world.
Example
The following class uses private access control −
Here, the format variable of the Logger class is private, so there's no way for
other classes to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String),
which sets its value.
Example
The following function uses public access control −
Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
Example
The following parent class uses protected access control, to allow its child
class override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Methods declared private are not inherited at all, so there is no rule for
them.
Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected,
public and default modifier.
Like class, interface can also be nested and can have access specifiers.
class Outer {
// Simple nested inner class
class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
As a side note, we can’t have static method in a nested inner class because an
inner class is implicitly associated with an object of its outer class so it
cannot define any static method for itself. For example the following program
doesn’t compile.
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
}
class Inner {
public static void main(String[] args){
System.out.println("inside inner class Method");
}
Output:
An interface can also be nested and nested interfaces have some interesting
properties. We will be covering nested interfaces in the next post.
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
Output
Inside outerMethod
Inside innerMethod
Method Local inner classes can’t use local variable of outer method until that
local variable is not declared as final. For example, the following code
generates compiler error (Note that x is not final in outerMethod() and
innerMethod() tries to access it)
class Outer {
void outerMethod() {
int x = 98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x= "+x);
Output:
But the following code compiles and runs fine (Note that x is final this time)
class Outer {
void outerMethod() {
final int x=98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x = "+x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodLocalVariableDemo {
public static void main(String[] args){
Outer x = new Outer();
x.outerMethod();
}
}
Output-:
Inside outerMethod
X = 98
The main reason we need to declare a local variable as a final is that local
variable lives on stack till method is on the stack but there might be a case
the object of inner class still lives on the heap.
Method local inner class can’t be marked as private, protected, static and
transient but can be marked as abstract and final, but not both at the same
time.
Output
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
Output
In the above code, we have two class Demo and Flavor1Demo. Here demo act as
super class and anonymous class acts as a subclass, both classes have a method
show(). In anonymous class show() method is overridden.
interface Hello {
void show();
}
Output:
i am in anonymous class
Important terms :
• Once we made object eligible for garbage collection, it may not destroy
immediately by garbage collector. Whenever JVM runs Garbage Collector
program, then only object will be destroyed. But when JVM runs Garbage
Collector, we can not expect.
• We can also request JVM to run Garbage Collector. There are two ways to do
it :
1. Using System.gc() method : System class contain static method
gc() for requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows
the application to interface with the JVM in which the
application is running. Hence by using its gc() method, we can
request JVM to run Garbage Collector.
// Java program to demonstrate requesting
// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args)
InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();
@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize()
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " +
this);
}
}
Output:
Note :
Finalization
• Just before destroying an object, Garbage Collector calls finalize()
method on the object to perform cleanup activities. Once finalize() method
completes, Garbage Collector destroys that object.
• finalize() method is present in Object class with following prototype.
protected void finalize() throws Throwable
Note :
3. http://www.javacjava.com/tutorials.aspx
4. https://www.javatpoint.com/java-tutorial
5. https://way2java.com/java-lang/
6. https://www.tutorialspoint.com/java/
7. www.studytonight.com/java/
8. https://beginnersbook.com/2013/05/
9. www1.fs.cvut.cz/cz/u12110/prt/java/
11. https://www.guru99.com/
12. www.c4learn.com/java/
13. www.geeksforgeeks.org/
14. www.sitesbay.com/java/
15.https://www.go4expert.com/articles/initialization-block-java-t1254/