Unit 2 Classes and Objects
Unit 2 Classes and Objects
2.1 Class
▪ A class is a user defined data type.
▪ Class is a template or blueprint for creating objects.
▪ Class may contain variables, methods and constructors.
2.2 Object
▪ An object is an instance of a class.
▪ Objects have states, behaviors and identity.
▪ The example of an intangible object is the banking system.
▪ An object has three characteristics:
o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an object
such as deposit, withdraw, etc.
o Identity: an object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user.
2.2.1 To create object
▪ An object is created from a class.
▪ The new keyword is used to create new objects. The new operator
dynamically allocates memory for an object at run time and returns
a reference to it. Then this reference is stored in the variable. Thus,
in Java all class objects must be dynamically allocated.
▪ Syntax: className object = new className();
1|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
public class Main
{
int x=5;
public static void main(String args[])
{
Main myobj = new Main();
System.out.println(myobj.x);
}
}
2|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
▪ Suppose you need to create a program to create a circle and color it.
You can create two methods:
• A method to draw the circle
• A method to color the circle
▪ In Java, there are two types of methods:
1. User-defined methods
o We can create our own method based on our requirements.
2. Standard library methods
o These are built-in methods in java that are available to use.
1. User-defined method
➢ Declaring a Java Method
Syntax for declaring java method
modifier static returnType nameOfMethod (parameter1,
parameter2, …)
{
// method body
}
o modifier – It defines access types whether the method is
public, private and so on.
o static – If we use the static keyword, it can be accessed
without creating objects.
For example, the sqrt() method of standard Math class is
static. Hence, we can directly call Math.sqrt() without
creating an instance of Math class.
o returnType – It specifies what type of value a method
returns.
For example, if a method has an int return type then it
returns an integer value. If a method does not return a
value, its return type is void.
o methodName – It is an identifier that is used to refer to
the particular method in a program.
3|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
o parameter1/parameter2 – These are values pass to a
method. We can pass any number of arguments to a
method.
Example:
public static int addNumbers(int num)
{
//method body
}
➢ Calling a method in Java
▪ Suppose, we have declare a method named addNumbers().
Now, to use the method we need to call it.
▪ Syntax:
//calls method
addNumbers(5);
Example: // Calling Methods using object
public class MainNew
{
//create a method
public int addNumbers(int a, int b)
{
int sum = a+b;
//return value
return sum;
}
public static void main(String args[])
{
int num1 = 25;
int num2 = 15;
//create an object of Main
MainNew obj = new MainNew();
//calling method
int result = obj.addNumbers(num1,num2);
4|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
System.out.println(“Sum is: “ +result);
}
}
o Here, we have created a method named addNumbers(). The
method takes two parameters a and b.
o We have called the method by passing two arguments num1
and num2.
o Since, the method is returning some value, we have stored the
value in the result variable.
Example: // Java method Return Type
public class ReturnType
{
//create a method
public static int square(int num)
{
//return statement
return num * num;
}
public static void main(String args[])
{
int result;
//call the method
//store returned value to result
result = square(10);
System.out.println("squared value of 10:" + result);
}
}
o Here, we have created a method named square(). The method
takes a number as its parameter and returns the square of the
number.
5|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
o Here, we have mentioned the return type of the method as int.
Hence, the method should always return an integer value.
▪ Note: If the method does not return any value, we use the void
keyword as the return type of the method.
Example: //java method void keyword
public class NoReturnType
{
public void square(int n)
{
int s=n*n;
System.out.println("square is" + s);
}
public static void main(String args[])
{
NoReturnType nr = new NoReturnType();
nr.square(10);
}
}
➢ Method parameters in java
▪ A method parameter is a value accepted by the method. A
method can have any number of parameters.
▪ Example:
//method with two parameters
int addNumbers(int a, int b)
{
//code
}
//method with no parameter
int addNumbers()
{
//code
}
6|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
▪ If a method is created with parameters, we need to pass the
corresponding values while calling the method.
▪ Example:
//calling the method with two parameters
addNumbers(25, 15);
//calling the method with no parameter
addNumbers();
Example: //Method Parameters
class MethodParameters
{
// method with no parameter
public void display1()
{
System.out.println("Method without parameter");
}
// method with single parameter
public void display2(int a)
{
System.out.println("Method with a single parameter: " + a);
}
public static void main(String[] args)
{
// create an object of Main
MethodParameters obj = new MethodParameters();
// calling method with no parameter
obj.display1();
+// calling method with the single parameter
obj.display2(24);
}
}
o Here, the parameter of the method is int. Hence, if we pass any
other data type instead of int, the compiler will throw an error.
o It is because java is a strongly typed language.
7|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Standard library methods
▪ The standard library methods are built-in methods in Java that are
readily available for use.
▪ These standard libraries come along with the Java Class
Library(JCL) in a java archive(*.jar) file with JVM and JRE.
▪ For example:
o sqrt() is a method of Math class. It returns the square root of a
number.
Example:
public class StandardLib
{
public static void main(String args[])
{
//using the sqrt() method.
System.out.println(“Square root of 4 is:” + Math.sqrt(4));
}
}
2.4 What are the advantages of using methods?
1. The main advantage is code reusability. We can write a method
once, and use it multiple times. We do not have to rewrite the entire
code each time. Think it as, “write once, reuse multiple times”.
2. Methods make code more readable and easier to debug.
2.5 Access Modifiers
▪ Access modifiers are used to set the accessibility (visibility) of
classes, interfaces, variables, methods, constructors, data members
and the setter methods.
▪ Example:
class Car
{
public void method1() {…}
private void method2() {…}
}
8|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
o Here, we have declared two methods: method1() and
method2().
o method1() is public – This means it can be accessed by other
classes.
method2() is private – This means it can not be accessed by
other classes.
▪ Types of Access Modifier
1. Default
2. Private
3. Protected
4. Public
1. Default
➢ When no access modifier is specified for a class, method or data
member, it is said to be having the default access modifier by
default.
➢ The default access modifier are accessible only within the same
package.
9|Page
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
package p1;
class DefMod
{
void display()
{
System.out.println(“Hello World”);
}
}
import p1.*;
//this class contains default modifier
class DefaultModifi
{
public static void main(String args[])
{
//accessing class DefMod from package p1
DefaultModifi dm = new DefaultModifi();
dm.display();
}
}
➢ Here, we have created two packages and the classes in the
packages will be having the default access modifiers and we will
try to access a class from one package from a class of second
package.
2. Private
➢ It is specified using the private keyword.
➢ When variables and methods are declared private, they cannot be
accessed outside of the class.
➢ Classes or Interfaces can not be declared as private.
10 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class Data
{
// private variable
private String name;
}
public class PrivateModifi
{
public static void main(String[] main)
{
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Programiz";
}
}
➢ Here, we have declared a private variable named name.
➢ When we run the program, we will get the following error:
PrivateModifi.java:13: error: name has private access in Data
d.name = "Programiz";
➢ The error is generated because we are trying to access the private
variable of the Data class from the PrivateModifi class.
➢ If we need to access the private variables, we can use the getters
and setters method.
11 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class Data
{
private String name;
// getter method
public String getName()
{
return this.name;
}
// setter method
public void setName(String name)
{
this.name= name;
}
}
public class PrivateGet
{
public static void main(String[] main)
{
Data d = new Data();
13 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
4. Public
➢ This modifier is specified using the public keyword.
➢ When methods, variables, classes are declared public, then we can
access them from anywhere.
➢ The public access modifier has no scope restriction.
Example:
// Animal.java file
class Animal
{
// public variable
public int legCount;
// public method
public void display()
{
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// PublicMain.java
public class PublicMain
{
public static void main(String[] args)
{
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}
➢ Here, the public variable legCount is accessed from the
PublicMain class.
14 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ The public method display() is accessed from the PublicMain
class.
2.6 Constructor
▪ A constructor has the same name as its class and does not have any
return type. It is called when an object of the class is created.
▪ Every time an object is created using the new() keyword, at least one
constructor is called. It calls a default constructor.
▪ If a class doesn’t have a constructor, the java compiler automatically
creates a default constructor during run time. The default constructor
initializes instance variables with default values.
▪ For example, the int variable will be initialized to 0.
▪ For example:
class Test{
Test(){
//constructor body
}
}
▪ Here, Test() is a constructor. It has the same name as that of the class
and doesn’t have a return type.
15 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class MainConstruct {
private String name;
// constructor
MainConstruct(){
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args)
{
// constructor is invoked while
// creating an object of the MainConstruct class
MainConstruct obj = new MainConstruct();
System.out.println("The name is " + obj.name);
}
}
}
2.6.1 Rules for creating Constructor
1. Constructor name must be the same as its class name.
2. A constructor must have no explicit return type.
3. We can use access modifiers while declaring a constructor.
2.6.2 Types of Constructor
▪ There are three types of constructors:
1. No argument constructor
2. Parameterized constructor
1. No argument constructor
➢ A constructor that has no parameter is known as the No-
argument or Zero argument constructor.
16 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class Geek
{
int num;
String name;
// this would be invoked while an object of that class is created.
Geek()
{
num=10;
name="Java Language";
}
}
class MainCons
{
public static void main(String[] args)
{
Geek geek1 = new Geek();
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}
➢ Using Multiple classes
o You can also create an object of a class and access it in another
class. This is used for better organization of classes(one class
has all the attributes and methods, while the other class holds
the main() method.)
2. Parameterized constructor
➢ A constructor that has parameters is known as parameterized
constructor.
➢ Parameters are added to a constructor in the same way that they
are added to a method, just declare them inside the parentheses
after the constructor’s name.
17 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example: //Parameterized Constructor
class MyClass
{
int x;
// Following is the constructor
MyClass(int i )
{
x = i;
}
}
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
2.6.3 Constructor Overloading
➢ We can overload constructors like methods. The constructor
overloading can be defined as the concept of having more than
one constructor with different parameters.
18 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
public class Student
{
int id;
String name;
Student()
{
//System.out.println("constructor without parameter");
}
Student(int i,String s)
{
id=i;
name=s;
}
public static void main(String args[])
{
System.out.println("Constructor without parameters values");
Student s1=new Student();
System.out.println("Student id:" + s1.id + "\n Student name:"
+ s1.name);
19 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
▪ Moreover, you can add new methods and fields in your current class
also.
▪ With the use of inheritance the information is made manageable in
a hierarchical order.
▪ Inheritance represents the Is-A relationship which is also known
as a parent-child relationship.
▪ The extends keyword is used to perform inheritance in Java.
▪ Syntax:
class derived-class extends base-class
{
//method and fields
}
2.7.1 Terminology in Inheritance
1. Class: Class is a set of objects which have common properties. Class
is not a real world entity. It is just a template or blueprint from which
objects are created.
2. Super class / Parent class: The class whose features are inherited
is known as a superclass.
3. Sub class / Child class: The class that inherits the other class is
known as a subclass.
4. Reusability: Reusability is a mechanism that allows you to reuse
the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in
the previous class.
2.7.2 Types of Inheritance
1. Single Inheritance
➢ In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for
the derived class B.
20 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking");
}
}
class SingleInherit
{
public static void main(String args[])
{
Dog d = new Dog();
d.bark();
d.eat();
}
}
21 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Multilevel Inheritance
➢ In multilevel inheritance, a derived class will be inheriting a base
class, and as well as the derived class also acts as the base class
for other classes.
➢ In the below image, class A serves as a base class for the derived
class B, which in turn serves as a base class for the derived class
C.
22 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping");
}
}
class MultilevelInherit
{
public static void main(String args[])
{
BabyDog d = new BabyDog();
d.bark();
d.eat();
d.weep();
}
}
3. Hierarchical Inheritance
➢ When two or more classes inherits a single class, it is known as
hierarchical inheritance.
23 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ In the below image, class A serves as a base class for the derived
class B, C and D.
Example:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class HierarchiInherit
{
public static void main(String args[])
{
24 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Cat c=new Cat();
c.meow();
c.eat();
Dog d=new Dog();
d.bark();
//c.bark(); //c.t.error
}
}
4. Multiple Inheritance (through interface)
➢ In multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes.
➢ Java does not support multiple inheritances with classes.
➢ In java, we can achieve multiple inheritances only through
Interfaces.
25 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ In the above figure, class A and class Bare two parent classes
inherited by class C.
➢ Now both classes A and B have a method with the same name i.e.
print(). So, when class C inherits A and B, then it will get both
versions of the print() method.
➢ In this case, class C will not know which method it should inherit.
➢ This ambiguous situation arises in the case of multiple inheritance.
5. Hybrid Inheritance
➢ Hybrid inheritance is a combination of two or more types of
inheritance.
➢ In the image below, we have combined hierarchical and multiple
inheritance to form a hybrid inheritance.
26 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.8 Polymorphism in Java
▪ The word polymorphism means having many forms. We can define
polymorphism as the ability of a message to be displayed in more
than one form.
▪ Example: A person at the same time can have different
characteristics. Like a man at the same time is a father, a husband,
an employee. So the same person possesses different behavior in
different situations. This is called polymorphism.
▪ Polymorphism allows us to perform a single action in different
ways.
▪ The word “poly” means many and “morphs” means forms, so it
means many forms.
▪ Polymorphism is divided into two types:
1. Compile-time polymorphism
2. Runtime polymorphism
1. Compile-time polymorphism
➢ It is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or operator
overloading. But java doesn’t support the operator overloading.
➢ Method Overloading: When there are multiple functions with
the same name but different parameters then these functions are
said to be overloaded. This is called method overloading.
➢ For example:
void func() {…..}
void func(int a) {…..}
float func(double a) {…..}
float func(int a, float b) {…..}
➢ Method overloading is one of the way through which java
supports polymorphism.
➢ Polymorphism is a concept of object oriented programming that
deal with multiple forms.
27 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ Method overloading can be done in two ways:
a. By changing number of arguments
b. By changing the data type of arguments
28 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
b. By changing the data type of arguments
Example:
class MethodOverloading2
{
// this method accepts int
public static void display(int a)
{
System.out.println("Got Integer data." +a);
}
// this method accepts String object
public static void display(String a)
{
System.out.println("Got String object." +a);
}
public static void main(String[] args)
{
display(1);
display("Hello");
}
}
➢ Why method overloading is not possible by changing the
return type of method only?
➢ In java, method overloading is not possible by changing the
return type of the method only because of ambiguity.
➢ Example:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));//ambiguity
}
}
29 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Runtime polymorphism
➢ During Inheritance in Java, if the same method is present in both
the superclass and the subclass. Then the method in the subclass
overrides the same method in the superclass. This is called
method overriding.
➢ Here, an overridden method is called through the reference
variable of a superclass.
Example:
// Class 1
class Parent
{
void Print()
{
System.out.println("parent class");
}
}
// Class 2
class subclass1 extends Parent
{
void Print()
{
System.out.println("subclass1");
}
}
// Class 3
class subclass2 extends Parent
{
// Method
void Print()
{
System.out.println("subclass2");
}
}
// Main class
class Overriding
{
30 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
public static void main(String[] args)
{
// Creating object of class 1
Parent a;
// Now we will be calling print methods inside main() method
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
2.9 Encapsulation
▪ Encapsulation is a process of wrapping code and data together into
a single unit.
▪ The variables of a class will be hidden from other classes and can be
accessed only through the methods of their current class. Therefore,
it is also known as data hiding.
▪ To achieve encapsulation in java –
o Declare the variables of a class as private.
o Provide public setter and getter methods to modify and view
the variables values.
Example:
class EncapTest
{
private String name;
private String idNum;
private int age;
public int getAge()
{
return age;
}
public String getName()
{
return name;
31 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
}
public String getId()
{
return idNum;
}
public void setAge(int newAge)
{
age = newAge;
}
public void setName(String newName)
{
name = newName;
}
public void setIdNum( String newId)
{
idNum = newId;
}
}
public class RunEncap
{
public static void main(String[] args)
{
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("123");
System.out.println("Name : " + encap.getName());
System.out.println(" Age : " + encap.getAge());
System.out.println(" Id : " + encap.getId());
}
}
32 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.10 this and super keyword
2.10.1 this keyword
▪ In Java, this keyword is a reference variable that refers to the current
object of a method or a constructor.
▪ The main purpose of using this keyword in java is to remove the
confusion between class attributes and parameters that have same
names.
▪ Following are various uses of “this” keyword in Java:
1. It can be used to refer instance variable of current class
2. It can be used to invoke or initiate current class constructor
3. It can be used to invoke current class method
4. It can be passed as an argument in the method call
5. It can be passed as an argument in the constructor call
6. It can be used to return the current class instance
1. Instance variable of current class:
Example:
class Test
{
//instance variable
int a;
int b;
//parameterized constructor
Test(int a, int b) //local variable
{
this.a = a;
this.b = b;
}
void display()
{
System.out.println(“value of a:” + a + “value of b:” +b);
}
public static void main(String args[])
{
33 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Test obj = new Test(10,20);
obj.display();
}
}
➢ Here, instance variable and constructor parameters are same. During
execution, compiler is confused. Whether “a” on the left side of the
assigned operator is the instance variable or the local variable.
Hence, it does not set the value of “a” when the method Test() is
called. So, we will use this to assign values of parameters to instance
variables.
2. Calling constructor using this keyword
a. Calling parameterized constructor from default constructor
Example:
class ThisConst
{
//default constructor
ThisConst()
{
//call parameterized constructor into default constructor
this(10,20);
System.out.println("default");
}
//parameterized constructor
ThisConst(int a,int b)
{
System.out.println("the value of a:" + a + "the value of b:" +b);
}
public static void main(String args[])
{
ThisConst obj = new ThisConst();
}
}
34 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
b. Calling default constructor from parameterized constructor
Example:
class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class ThisConst2
{
public static void main(String args[])
{
A a=new A(10);
}
}
3. Accessing method using this keyword
➢ You may invoke the method of the current class by using this
keyword.
➢ If you don’t use this keyword, compiler automatically adds this
keyword while invoking the method.
35 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class ThisMeth
{
public static void main(String args[])
{
A a = new A();
a.n();
}
}
2.10.2 super keyword
▪ 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.
➢ Using of Java super keyword
1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
36 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
1. super can be used to refer immediate parent class instance
variable
➢ We can use super keyword to access the data member or field of
parent class.
➢ It is used if parent class and child class have same fields.
Example:
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
➢ In the above example, Animal and Dog both classes have a
common property color.
➢ If we print color property, it will print the color of current class
by default.
➢ To access the parent property, we need to use super keyword.
37 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. super can be used to invoke parent class method
➢ The super keyword can also be used to invoke parent class
method.
➢ It should be used if subclass contains the same method as parent
class.
Example:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
eat();
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
38 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
d.work();
}
}
➢ In the above example, Animal and Dog both classes have eat()
method. If we call eat() method from Dog class, it will call the eat()
method of Dog class by default.
➢ To call the parent class method, we need to use super keyword.
3. super is used to invoke parent class constructor
➢ The super keyword can also be used to invoke the parent class
constructor.
Example:
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
39 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.11 Static member, static block and static class
2.11.1 Static member (variable)
➢ A static variable is common to all the instances (or objects) of the
class because it is a class level variable.
➢ In other words, you can say that only a single copy of static
variable is created and shared among all the instances of the class.
➢ Memory allocation for such variables only happens once when the
class is loaded in the memory.
➢ Static variables are also known as class variables.
➢ Unlike non-static variables, such variables can be accessed
directly in static and non-static methods.
1. Accessing static variable directly without creating object
Example:
class StaticVar
{
static int var1;
static String var2;
40 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Static variables are shared among all the instances of class
Example:
class StaticVarExp
{
static int var1=77; //static integer variable
String var2; //non-static string variable
ob2.var1=99;
ob2.var2="I am object2";
/*This will overwrite the value of var1 because var1 has a single
copy shared among both the objects.*/
System.out.println("ob1 integer:" +ob1.var1);
System.out.println("ob1 string:" +ob1.var2);
System.out.println("ob2 integer:" +ob2.var1);
System.out.println("ob2 string:" +ob2.var2);
}
}
41 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.11.2 Static block
➢ Static block is used for initializing the static variables.
➢ This block gets executed when the class is loaded in the memory.
➢ A class can have multiple static blocks, which will execute in the
same sequence in which they have been written into the program.
1. Single static block
Example:
class StaticBlock1
{
static int n;
static String str;
static
{
n=50;
str="static block";
}
public static void main(String args[])
{
System.out.println("value of n:" +n);
System.out.println("value of string:" +str);
}
}
42 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Multiple static block
Example:
class StaticMultiBlock
{
static int n;
static String str;
//First static block
static
{
System.out.println("First static block");
n=50;
str="Block1";
}
//Second static block
static
{
System.out.println("Second static block");
n=60;
str="Block2";
}
public static void main(String args[])
{
System.out.println(“The value of n:” +n);
System.out.println(“The value of str:” +str);
}
}
2.11.3 Static method
➢ When a method is declared with the static keyword, it is known
as the static method.
➢ Static methods can access class variables (static variables)
without using object (instance) of the class.
➢ Non-static methods and non-static variables can only be accessed
using objects.
43 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
➢ Static methods can be accessed directly in static and non-static
methods.
➢ Static methods have several restrictions:
o They can only directly call other static methods.
o They can only directly access static data.
o They cannot refer to this or super.
Example:
class Smethod
{
static int i = 10;
static String s = "Hello";
//This is a static method
static void a()
{
System.out.println("i:"+i);
System.out.println("s:"+s);
}
public static void main(String args[])
{
a();
}
}
44 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
// Java program to demonstrate static method accessed directly
in static and non-static method
class Test
{
// static variable
static int a = 10;
// instance variable
int b = 20;
// static method
static void m1()
{
//a = 20;
System.out.println("the value of a:" +a);
}
// instance method
void m2()
{
m1(); //static method call in non-static method
System.out.println("from m2");
}
//static method
public static void main(String[] args)
{
//static method called in another static method
Test.m1(); //or m1();
//you need to have object to call this non-static method.
Test t = new Test();
t.m2();
}
}
45 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.11.4 Static class
➢ A class can be made static only if it is a nested class.
1. Nested static class doesn’t need reference of outer class.
2. A static class cannot access non-static members of the outer class.
Example:
class StaticClass
{
private static String str="Hello";
//static class
static class NestedClass
{
//non-static method
public void display()
{
System.out.println(str);
}
}
public static void main(String args[])
{
/*To create instance of nested class we didn't need the outer
class instance but for a regular nested class you would need
to create an instance of outer class first
*/
StaticClass.NestedClass obj = new StaticClass.NestedClass();
obj.display();
}
}
46 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.12 Abstraction
▪ Data abstraction is the process of hiding certain details from the user
and showing only essential information to the user.
▪ Abstraction can be achieved with either abstract classes or
interfaces.
▪ For example, when you consider the case of e-mail, complex details
such as what happens as soon as you send an e-mail, the protocol
your e-mail server uses are hidden from the user. Therefore, to send
an e-mail you just need to type the content , mention the address of
the receiver and click send.
2.12.1 Abstract class
▪ An abstract class must be declared with an abstract keyword.
▪ Abstract classes may or may not contain abstract methods. i.e,
methods without body (public void get();).
▪ But, if a class has at least one abstract method, then the class must
be declared abstract.
▪ If a class is declared abstract, it cannot be instantiated [we cannot
create objects of abstract classes].
▪ To use an abstract class, you have to inherit it from another class,
provide implementations to the abstract methods in it.
2.12.2 Abstract method
▪ A method which is declared as abstract and does not have
implementation is known as an abstract method.
▪ The implementation is provided by the subclass.
▪ An abstract class can have both abstract and regular methods.
47 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class TestAbstraction
{
public static void main(String args[])
{
Circle1 c = new Circle1();
c.draw();
Rectangle r = new Rectangle();
r.draw();
}
}
2.13 Interfaces
▪ An interface is a fully abstract class. It includes a group of abstract
methods without a body.
▪ We use the interface keyword to create an interface in Java.
▪ It is used to achieve abstraction and multiple inheritance in Java.
48 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.13.1 Interface declaration
▪ The interface keyword is used to declare an interface.
▪ 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.
▪ Interfaces have the following properties:
o An interface is implicitly abstract. You do not need to use the
abstract keyword while declaring an interface.
o Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
o Methods in an interface are implicitly public.
▪ Syntax:
interface <interface_name>
{
//declare constant fields
//declare methods that abstract by default.
}
▪ Example:
interface Language
{
public void getType();
public void getCode();
}
Here, Language is an interface.
It includes abstract methods: getType() and getCode().
2.13.2 Interface Implementations
▪ Like abstract classes, we cannot create objects of interfaces.
▪ To use an interface, other classes must implement it. We use the
implements keyword to implement an interface.
49 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
interface Polygon
{
void getArea(int length, int breadth)
}
//implement the polygon interface
class Rectangle implements Polygon
{
//implementation of abstract method
public void getArea(int length, int breadth)
{
System.out.println(“The area of the rectangle:”+(length*breadth));
}
}
class Main
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.getArea(5,6);
}
}
➢ In the above example, we have created an interface named Polygon.
The interface contains an abstract method getArea().
➢ Here, the Rectangle class implements Polygon and provides the
implementation of the getArea() method.
2.13.3 Multiple inheritance in Java by interface
▪ An interface contains variables and methods like a class but the
methods in an interface are abstract by default.
▪ Multiple inheritance by interface occurs if a class implements
multiple interfaces or also if an interface itself extends multiple
interfaces.
50 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
Example:
//Multiple Inheritance
interface AnimalEat
{
void eat();
}
interface AnimalTravel
{
void travel();
}
class Animal implements AnimalEat, AnimalTravel
{
public void eat()
{
System.out.println("Animal is eating");
}
public void travel()
{
System.out.println("Animal is travelling");
}
}
public class Demo
{
public static void main(String args[])
{
Animal a = new Animal();
a.eat();
a.travel();
}
}
51 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2.14 Take input from user using Scanner class
▪ Java Scanner class allows the user to take input from the console. It
belongs to java.util package.
▪ It is used to read the input of primitive types like int, double, long,
short, float and byte.
▪ Syntax:
Scanner sc = new Scanner(System.in);
▪ The above statement creates a constructor of the Scanner class
having System.in as an argument. It means it is going to read from
the standard input stream of the program.
▪ The java.util package should be import while using Scanner class.
2.14.1 Methods of Scanner class
▪ Java Scanner class provides the following methods to read different
primitive types:
Method Description
int nextInt() Reads a int value from the user
float nextFloat() Reads a float value from the user
double nextDouble() Reads a double value from the user
byte nextByte() Reads a byte value from the user
string nextLine() Reads a string value from the user
boolean nextBoolean() Reads a boolean value from the user
long nextLong() Reads a long value from the user
short nextShort() Reads a short value from the user
52 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
1. Example of integer input from user
Example:
import java.util.*;
class UserInput
{
public static void main(String[] args)
{
//System.in is a standard input stream
Scanner sc= new Scanner(System.in);
System.out.print("Enter first number:");
int a= sc.nextInt();
System.out.print("Enter second number:");
int b= sc.nextInt();
System.out.print("Enter third number:");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
53 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
2. Example of various types of input from user
Example:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name:");
//String input
String name = myObj.nextLine();
System.out.println("Enter age:");
//Numerical input
int age = myObj.nextInt();
System.out.println("Enter salary:");
double salary = myObj.nextDouble();
//Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
2.15 Command Line Arguments
▪ The java command-line argument is an argument i.e. passed at the
time of running the java program.
▪ The arguments passed from the console can be received in the java
program and it can be used as an input.
▪ We can pass both strings and primitive data types(int, double, float,
char, etc) as command line arguments
▪ These arguments convert into a string array and are provided to the
main() function as a string array argument.
▪ Internally, JVM wraps these command-line arguments into the
args[] array that we pass into the main() function. We can check
these arguments using args.length method.
54 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT
▪ JVM stores the first command-line argument at args[0], the second
at args[1], the third at args[2], and so on.
Example:
class CommandLine
{
public static void main(String[] args)
{
// Printing the first argument
System.out.println(args[0]);
}
}
55 | P a g e
By – Dr. Smruti H. Mehta M.L.Parmar College of Computer Science and IT