Wednesday, July 31, 2019



Chapter 2 Classes and Objects

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
A class in java can contain:

  • data member
  • method
  • constructor
  • block
  • class and interface
Syntax to declare a class:
  1. class <class_name>{  
  2.     data member;  
  3.     method;  
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
  • state: represents data (value) of an object.
  • behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
  • identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Object in Java



Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

 

Simple Example of Object and Class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.
  1. class Student1{  
  2.  int id;//data member (also instance variable)  
  3.  String name;//data member(also instance variable)  
  4.   
  5.  public static void main(String args[]){  
  6.   Student1 s1=new Student1();//creating an object of Student  
  7.   System.out.println(s1.id);  
  8.   System.out.println(s1.name);  
  9.  }  
  10. }  
Output:0 null
     

new keyword

The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of students

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects by invoking the displayInformation method.
  1. class Student2
  2. {    int rollno;  
  3.      String name;   
  4.        void insertRecord(int r, String n){  //method  
  5.       rollno=r;  
  6.     name=n;  
  7.  }   
  8.  void displayInformation()
  9. {      System.out.println(rollno+" "+name);}//method   
  10.        public static void main(String args[]){  
  11.        Student2 s1=new Student2();  
  12.        Student2 s2=new Student2();    
  13.        s1.insertRecord(111,"Karan");  
  14.        s2.insertRecord(222,"Aryan");   
  15.       s1.displayInformation();  
  16.        s2.displayInformation();   
  17.  }  
  18. }  
Output
       111 Karan
       222 Aryan
     

Java Garbage Collection

In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Constructor in Java

  1. Types of constructors
    1. Default Constructor
    2. Parameterized Constructor
  2. Constructor Overloading
  3. Does constructor return any value
  4. Copying the values of one object into another
  5. Does constructor perform other task instead initialization
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
 

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default 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.
  1. class Bike1{  
  2. Bike1(){System.out.println("Bike is created");}  
  3. public static void main(String args[]){  
  4. Bike1 b=new Bike1();  
  5. }  
  6. }  
Output:
Bike is created

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values
class Student3{  
int id;  
String name;   
void display(){System.out.println(id+" "+name);}    
public static void main(String args[]){  
Student3 s1=new Student3();  
Student3 s2=new Student3();  
s1.display(); 
s2.display();  
}  
Output:
0 null
0 null

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized 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.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
15.       s2.display();  
16.      }  }  
Output:
111 Karan
222 Aryan

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

class Student5{  
    int id;  
    String name;  
    int age;  
    Student5(int i,String n){
    id = i;  
    name = n; 
    }  
    Student5(int i,String n,int a){
    id = i;   
 name = n;  
    age=a; 
    }  
    void display(){System.out.println(id+" "+name+" "+age);}  
    public static void main(String args[]){  
    Student5 s1 = new Student5(111,"Karan");  
    Student5 s2 = new Student5(222,"Aryan",25);  
    s1.display();  
    s2.display();  
   }  }  
Output:
111 Karan 0
222 Aryan 25

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
  1. class Student6{  
  2.     int id;  
  3.     String name;  
  4.     Student6(int i,String n){  
  5.     id = i;  
  6.     name = n;  
  7.     }  
  8.       
  9.     Student6(Student6 s){  
  10.     id = s.id;  
  11.     name =s.name;  
  12.     }  
  13.     void display(){System.out.println(id+" "+name);}  
  14.    
  15.     public static void main(String args[]){  
  16.     Student6 s1 = new Student6(111,"Karan");  
  17.     Student6 s2 = new Student6(s1);  
  18.     s1.display();  
  19.     s2.display();  
  20.    }  
  21. }  
Output:
111 Karan
111 Karan

Inheritance in Java

  1. Inheritance
  2. Types of Inheritance
  3. Why multiple inheritance is not possible in java in case of class?
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
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 parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  
The extends keyword indicates that you are making a new class that derives from an existing class.
class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  
Output
 Programmer salary is:40000.0
 Bonus of 
programmer is:10000

In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.
                                                     

 






Types of inheritance in java








On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class


Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
 Public Static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  
Output
 Compile Time Error

 

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
  • It is used to achieve fully abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in the A class.
interface printable{  
void print();  
}  
  
class A6 implements printable{  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
A6 obj = new A6();  
obj.print();  
 }  
}  
Output
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
interface Printable{  
                                              void print();  
                                         }    
interface Showable{  
void show();  
       }    
class A7 implements  Printable,Showable{  
  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  
Output:Hello
       Welcome
 

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just 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.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java
  1. Abstract class (0 to 100%)
  2. Interface (100%)
 
Abstract class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class
1.     abstract class A{}  
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Example abstract method
  1. abstract void printStatus();//no body and abstract  

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
  1. abstract class Bike{  
  2.   abstract void run();  
  3. }  
  4. class Honda4 extends Bike{  
  5. void run(){System.out.println("running safely..");}  
  6. public static void main(String args[]){  
  7.  Bike obj = new Honda4();  
  8.  obj.run();  
  9. }  
  10. }  
Output
running safely..

interface

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-abstract methods.
Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance.
Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
4) Abstract class can have static methods, main method and constructor.
Interface can't have static methods, main method or constructor.
5) Abstract class can provide the implementation of interface.
Interface can't provide the implementation of abstract class.
6) The abstract keyword is used to declare abstract class.
The interface keyword is used to declare interface.
7) Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splender extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splender();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  
Output
        Output:running safely with 60km.
 

Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
class Bank{  
int getRateOfInterest(){return 0;}  
}    
class SBI extends Bank{            

int getRateOfInterest(){return 8;}  
}   
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}    
class Test3{  
public static void main(String args[]){  
Bank b1=new SBI();  
Bank b2=new ICICI();  
Bank b3=new AXIS();  
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. method must have same name as in the parent class
  2. method must have same parameter as in the parent class.
  3. must be IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
class Vehicle{  
void run(){System.out.println("Vehicle is running");}  
}  
class Bike2 extends Vehicle{  
void run(){System.out.println("Bike is running safely");}  
  
public static void main(String args[]){  
Bike2 obj = new Bike2();  
obj.run();  
}  
Output
Output:Bike is running safel
 
 

Method Overloading in Java

  1. Different ways to overload the method
  2. By changing the no. of arguments
  3. By changing the datatype
  4. Why method overloading is not possible by changing the return type
  5. Can we overload the main method
  6. method overloading with Type Promotion
If a class have multiple methods by same name but different 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. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java
  1. By changing number of arguments
  2. By changing the data type
 

Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.
class Calculation{  
  void sum(int a,int b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}    
  public static void main(String args[]){  
  Calculation obj=new Calculation();  
  obj.sum(10,10,10);  
  obj.sum(20,20);  
  
  }  
}  
Output:30
       40
 
 
No.
Method Overloading
Method Overriding
1)
Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2)
Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
3)
In case of method overloading, parameter must be different.
In case of method overriding, parameter must be same.
4)
Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
5)
In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.
Return type must be same or covariant in method overriding.
 

Java Inner Class

Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.

Syntax of Inner class

class Java_Outer_class
{  
//code  
 class Java_Inner_class
{  
 //code  
                       }  
}  

Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of 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 Outer_Demo {
   int num;  
   // inner class
   private class Inner_Demo {
      public void print() {
         System.out.println("This is an inner class");
      }
   }  
   // Accessing he inner class from the method within
   void display_Inner() {
      Inner_Demo inner = new Inner_Demo();
      inner.print();
   }
}  
public class My_class {
   public static void main(String args[]) {
      // Instantiating the outer class
      Outer_Demo outer = new Outer_Demo();     
      // Accessing the display_Inner() method.
      outer.display_Inner();
   }
}
Output
This is an inner class.

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
  1. private
  2. default
  3. protected
  4. public

1) private access modifier

The private access modifier is accessible only within class.

2) default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.
Access Modifier
within class
within package
outside package by subclass only
outside package
Private
Y
N
N
N
Default
Y
Y
N
N
Protected
Y
Y
Y
N
Public
Y
Y
Y
Y

java package:-
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.


How to access package from another package?

There are three ways to access the package from outside the package.
  1. import package.*;
  2. import package.classname;
  3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.

Example of package that import the packagename.*

//save by A.java 
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java 
package mypack;
import pack.*;  
class B{  
  public static void main(String args[]){  
   A obj = new A();
   obj.msg();  
}  
Output:Hello
 
 
STEPS for developing a User Defined PACKAGE:
  1.  Choose the appropriate package name, the package name must be a JAVA valid variable name
    and we showed ensure the package statement must be first executable statement.
  2.  Choose the appropriate class name or interface name and whose modifier must be public. The modifier of Constructors of a class must be public.
  3.  The modifier of the methods of class name or interface name must be public.
  4.  At any point of time we should place either a class or an interface in a package and give the file
  5. name as class name or interface name with extension .java
Built-in Packages
These packages consists of a large number of classes which are a part of Java API. For e.g, we have used java.io package previously which contain classes to support input / output operations in Java. Similarly, there are other packages which provides different functionality.
Some of the commonly used built-in packages are shown in the table below :
Package Name
Description
java.lang
Contains language support classes ( for e.g classes which defines primitive data types, math operations, etc.) . This package is automatically imported.
java.io
Contains classes for supporting input / output operations.
java.util
Contains utility classes which implement data structures like Linked List, Hash Table, Dictionary, etc and support for Date / Time operations.
java.applet
Contains classes for creating Applets.
java.awt
Contains classes for implementing the components of graphical user interface ( like buttons, menus, etc. ).
java.net
Contains classes for supporting networking operations.
Accessing classes in a package
Consider the following statements :
import java.util.*;

Primitive Type
Wrapper class
Primitive Type
Wrapper class
boolean
Boolean
int
Integer
char
Character
long
Long
byte
Byte
float
Float
short
Short
double
Double

Wrapper class in Java

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive


 




FYBBA(CA) Semester-II Practical Lab Assignment RDBMS

1 FYBBA(CA) Semester-II Practical Lab Assignment RDBMS Q1. Consider the following entities and their relationships. Client (client_no...