Java OOPs Concepts
Java OOPs Concepts
1. Object Oriented Programming 2. Advantage of OOPs over Procedure-oriented programming language 3. Difference between Objcet-oriented and Objcet-based programming language. we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc. Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented programming language. Smalltalk is considered as the first truly object-oriented programming language.
What we will learn in OOPs Concepts ? Advantage of OOPs Naming Convention Object and class Method overloading Constructor static keyword this keyword with 6 usage Inheritance Aggregation Method Overriding Covariant Return Type
super keyword Instance Initializer block final keyword Abstract class Interface Runtime Polymorphism Static and Dynamic Binding Downcasting with instanceof operator Package Access Modifiers Encapsulation Object Cloning
What is difference between object-oriented programming language and objectbased programming language?
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object based programming languages.
Naming convention
A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc.), but it is not mandatory to follow that is why it is known as convention not rule. Advantage: By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does.
class name
should begin with uppercase letter and be a noun e.g.String,System,Thread etc. should begin with uppercase letter and be an adjective (whereever possible).
Interface name e.g. Runnable,ActionListener etc. should begin with lowercase letter and be a verb. method name e.g. main(),print(),println(),actionPerformed() etc. should begin with lowercase letter variable name e.g. firstName,orderNumber etc. should be in lowercase letter. package name e.g. java,lang,sql,util etc. should be in uppercase letter. constants name e.g. RED,YELLOW,MAX_PRIORITY etc.
we will learn about the objects and classes. In object-oriented programming, we design a program using objects and classes. Object is the physical entity whereas class is the logical entity. A class works as a template from which we create the objects.
Object
A runtime entity that has state and behaviour is known as an object. For example: chair, table, pen etc. It can be tengible or intengible (physical or logical). An object has three characterstics:
state:represents the data of an object. behaviour:represents the behaviour of an object. identity:Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user, but 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 behaviour. 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.
Class
A class is a group of objects that have common property. It is a template or blueprint from which objects are created. A class in java can contain:
Output:0 null
Instance variable
A variable that is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when object(instance) is created. That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behavior of an object. Advantage of Method
new keyword
The new keyword is used to allocate memory at runtime.
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object. If you have to use an object only once, annonymous object is a good approach.
Output:Factorial is 120
If we have to perform only one operation, having the 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 behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly.
Output:30 40
Output:21.0 40
Question: Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on.
Output:40 60
void sum(long a,int b){System.out.println("b method invoked");} public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(20,20);//now ambiguity } } Output:Compile Time Error
One type is not depromoted implicitely for example double cannot be depromoted to any type implicitely.
Constructor
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 is a special type of method that is used to initialize the state of an object. Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is why it is known as constructor. Constructor is just like the instance method but it does not have any explicit return type.
1. Constructor name must be same as its class name 2. Constructor must have no explicit return type
Types of constructors
There are two types of constructors: 1. default constructor (no-arg constructor) 2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
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.
Parameterized constructor
A constructor that have parameter is known as parameterized constructor.
Constructor Overloading
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.
} void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan",25); s1.display(); s2.display(); } } Output:111 Karan 0 222 Aryan 25
Constructor must not have return type. Constructor is invoked implicitly. The java compiler provides a default constructor if you don't have any constructor.
Copying 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. 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 constructor.
//Program of Copying the values of one object to another class Student{ int id; String name; Student(int i,String n){
id = i; name = n; } Student(Student s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(s1); s1.display(); s2.display(); } } Output:111 Karan 111 Karan
static keyword
1. 2. 3. 4. 5. 6. 7. Static variable Program of counter without static variable Program of counter with static variable Static method Restrictions for static method Why main method is static ? Static block
8. Can we execute a program without main method ? The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be:
1. variable (also known as class variable) 2. method (also known as class method) 3. block
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. The static variable gets memory only once in class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once. Note:static field is shared by all objects.
static String college ="ITS"; Student(int r,String n){ rollno = r; name = n; } void display (){System.out.println(rollno+" "+name+" "+college);} public static void main(String args[]){ Student s1 = new Student (111,"Karan"); Student s2 = new Student (222,"Aryan"); s1.display(); s2.display(); } } Output:111 Karan ITS 222 Aryan ITS
have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.
class Counter{ int count=0;//will get memory when instance is created Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); }} Output:1 1 1
2) static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.
3)static block:
Is used to initialize the static data member. It is excuted before main method at the time of classloading.
this keyword
1. this keyword 2. Usage of this keyword 1. to refer the current class instance variable 2. to invoke the current class constructor 3. to invoke the current class method 4. to pass as an argument in the method call 5. to pass as an argument in the constructor call 6. to return the current class instance 3. Proving this keyword There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object.
6. this keyword can also be used to return the current class instance.
Suggestion:If you are beginner to java, lookup only two usage of this keyword.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. Understanding the problem without this keyword Let's understand the problem if we don't use this keyword by the example given below:
class student{ int id; String name; student(int id,String name){ id = id; name = name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ student s1 = new student(111,"Karan"); student s2 = new student(321,"Aryan"); s1.display(); s2.display(); } } Output:0 null 0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program: Program where this keyword is not required
class Student{
int id; String name; student(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student e1 = new Student(111,"karan"); Student e2 = new Student(222,"Aryan"); e1.display(); e2.display(); } } Output:111 Karan 222 Aryan
The this() constructor call should be used to reuse the constructor in 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.
class Student{ int id; String name; String city; Student(int id,String name){ this.id = id; this.name = name; } Student(int id,String name,String city){ this(id,name);//now no need to initialize id and name this.city=city; } void display(){System.out.println(id+" "+name+" "+city);} public static void main(String args[]){ Student e1 = new Student(111,"karan"); Student e2 = new Student(222,"Aryan","delhi"); e1.display(); e2.display(); } } Output:111 Karan null 222 Aryan delhi
3)The this keyword can be used to invoke current class method (implicitly).
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
class S{ void m(){ System.out.println("method is invoked"); } void n(){ this.m();//no need because compiler does it for you. } void p(){ n();//complier will add this to invoke n() method as this.n() } public static void main(String args[]){ S s1 = new S(); s1.p(); } } Output:method is invoked
public static void main(String args[]){ S s1 = new S(); s1.p(); } } Output:method is invoked
return this; }
Example of this keyword that you return as a statement from the method
class A{ A getA(){ return this; } void msg(){System.out.println("Hello java");} } class Test{ public static void main(String args[]){ new A().getA().msg(); } } Output:Hello java
Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent object. The idea behind inheritance is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new methods and fields to adapt your new class to new situations.Inheritance represents the IS-A relationship.
Syntax of Inheritance
class Subclass-name extends Superclass-name { //methods and fields }
The keyword extends indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.
Example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
class Employee{ int 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 Bonus of programmer is:10000
In the above example,Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Types of Inheritance:
Note:Multiple inheritance is not supported in java in case of class. When a class extends two classes i.e. known as multiple inheritance.For Example:
To reduce the complexity and simplify the language,multiple inheritance is not supported in java.For Example:
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? } }
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
class Employee{ int id; String name; Address address;//Address is a class ... }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{ int square(int n){ return n*n; } } class Circle{ Operation op;//aggregation double pi=3.14; double area(int radius){ op=new Operation(); int rsquare=op.square(radius);//code reusability (i.e. delegates the method call). return pi*rsquare; }
public static void main(String args[]){ Circle c=new Circle(); double result=c.area(5); System.out.println(result); } } Output:78.5
Code reuse is also best achieved by aggregation when there is no is-a relationship. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.
In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address.
Address.java
public class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } }
Emp.java
public class Emp { int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name); System.out.println(address.city+" "+address.state+" "+address.country); } public static void main(String[] args) { Address address1=new Address("gzb","UP","india"); Address address2=new Address("gno","UP","india"); Emp e=new Emp(111,"varun",address1); Emp e2=new Emp(112,"arun",address2); e.display(); e2.display(); } }
1. Understanding problem without method overriding 2. Can we override the static method 3. method overloading vs method overriding Having the same method in the subclass as declared in the parent class is known as method overriding. If a subclass provides a specific implementation of a method that is already provided by its super class, it is known as 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 Method Overriding: 1. method must have same name as in the parent class 2. method must have same parameter as in the parent class.
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.
void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Output:Bike is running safely
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.
super keyword:
super is a reference variable that is used to refer immediate parent class object.
Uses of super Keyword: 1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor. 3. super is used to invoke immediate parent class method.
In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.
Output:50
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the consructor.
Another example of super keyword where super() is provided by the compiler implicitely.
class Vehicle{ Vehicle(){System.out.println("Vehicle is created");} } class Bike extends Vehicle{ int speed; Bike(int speed){ this.speed=speed; System.out.println(speed); } public static void main(String args[]){ Bike b=new Bike(10); } } Output:Vehicle is created 10
In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.
public static void main(String args[]){ Student s=new Student(); s.display(); } } Output:welcome
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be directly but there can be performed extra operations while initilizing the instance variable in the instance initializer block. Que) What is the use of instance initializer block while we can directly assign a value in instance data member? For example:
class Bike{ int speed=100; }
Bike(){System.out.println("speed is "+speed);} {speed=100;} public static void main(String args[]){ Bike b1=new Bike(); Bike b2=new Bike(); } } Output:speed is 100 speed is 100
There are three places in java where you can perform operations: 1. method 2. constructor 3. block
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.
1. The instance initializer block is created when instance of the class is created. 2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call). 3. The instance initializer block comes in the order in which they appear.
class A{ A(){ System.out.println("parent class constructor invoked"); } } class B extends A{ B(){ super(); System.out.println("child class constructor invoked"); } {System.out.println("instance initializer block is invoked");} public static void main(String args[]){ B b=new B(); } } Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked
//Another example of instance initializer block that is invoked after super() class A{ A(){ System.out.println("parent class constructor invoked"); } } class B extends A{ B(){ super(); System.out.println("child class constructor invoked"); } B(int a){ super(); System.out.println("child class constructor invoked "+a); } {System.out.println("instance initializer block is invoked");} public static void main(String args[]){ B b1=new B();
B b2=new B(10); } } Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked parent class constructor invoked instance initializer block is invoked child class constructor invoked 10
final keyword:
1. 2. 3. 4. 5. 6. 7. 8. Final variable Final method Final class Is final method inherited ? Blank final variable Static blank final variable Final parameter Can you declare a final constructor
The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be: 1. variable 2. method 3. class The final keyword can be applied with the variables, that have no value it is called blank final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1)final variable:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike obj=new Bike(); obj.run(); } } Output:Compile Time Error
2)final method
If you make any method as final, you cannot override it.
3)final class:
If you make any class as final, you cannot extend it.
} Output:70
Abstraction
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. Abstraction lets you focus on what the object does instead of how it does it.
Abstract class
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.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract class Bike{ abstract void run(); } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); } } Output:running safely..
Note: An abstract class can have data member,abstract method,method body,constructor and even main() method.
//example of abstract class that have method body abstract class Bike{ abstract void run(); void changeGear(){System.out.println("gear changed");} } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.changeGear(); } } Output:running safely.. gear changed //example of abstract class having constructor, field and method abstract class Bike { int limit=30; Bike(){System.out.println("constructor is invoked");} void getDetails(){System.out.println("it has two wheels");} abstract void run(); } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.getDetails(); System.out.println(obj.limit); } } Output:constructor is invoked running safely.. it has two wheels 30
Rule: If there is any abstract method in a class, that class must be abstract.
class Bike{ abstract void run(); } Output:compile time error
Rule: If you are extending any abstact class that have abstract method, you must either provide the implementation of the method or make this class abstract.
The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{ void a(); void b(); void c(); void d(); } abstract class B implements A{ public void c(){System.out.println("I am C");} } class M extends B{ public void a(){System.out.println("I am a");} public void b(){System.out.println("I am b");} public void d(){System.out.println("I am d");} } class Test{ public static void main(String args[]){ A a=new M(); a.a(); a.b(); a.c(); a.d(); }} Output:I am a I am b I am c I am d
Interface
1. 2. 3. 4. 5. 6. Interface Example of Interface Multiple inheritance by Interface Why multiple inheritance is supported in Interface while it is not supported in case of class. Marker Interface Nested Interface
An interface is a blueprint of a class. It has static constants and abstract methods. The interface is a mechanism to achieve abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.
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.
The java compiler converts methods of interface as public and abstract, data members as public,final and static bydefault.
interface printable{ void print(); } class A implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A obj = new A(); obj.print(); } } Output:Hello
Que) Multiple inheritance is not supported in case of class but it is supported in case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implmentation is provided by the implementation class. For example:
interface Printable{ void print(); } interface Showable{ void print(); } class A implements Printable,Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A obj = new A(); obj.print(); } } Output:Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class A, so there is no ambiguity.
Note: A class implements interface but One interface extends another interface .
interface Printable{ void print(); } interface Showable extends Printable{ void show(); } class A implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A obj = new A(); obj.print(); obj.show(); } } Output:Hello Welcome
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
interface printable{ void print(); interface MessagePrintable{ void msg(); } }
Runtime Polymorphism
1. 2. 3. 4. Runtime Polymorphism Upcasting Example of Runtime Polymorphism Runtime Polymorphism with data members
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. 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
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.For example:
class BabyDog extends Dog{ void eat(){System.out.println("drinking milk");} public Animal a1=new a2=new a3=new static void main(String args[]){ a1,a2,a3; Animal(); Dog(); BabyDog();
class Animal{ void eat(){System.out.println("animal is eating...");} } class Dog extends Animal{ void eat(){System.out.println("dog is eating...");} } class BabyDog extends Dog{ public static void main(String args[]){ Animal a=new BabyDog(); a.eat(); }} Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
About type:
1) variables have a type For example: int data=30; Here data variable is a type of int. 2) References have a type
class Dog{ public static void main(String args[]){ Dog d1;//Here d1 is a type of Dog } }
3) Objects have a type An object is an instance of particular java class,but it is also an instance of its superclass.
class Animal{} class Dog extends Animal{ public static void main(String args[]){ Dog d1=new Dog(); } }
static binding:
When type of the object is determined at compiled time(by the compiler), it is known as static binding. If there is any private,final or static method in a class,it is static binding.
Dynamic binding:
When type of the object is determined at run-time, it is known as dynamic binding.
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
instanceof operator
1. 2. 3. 4. 5. The instanceof operator Example of instanceof operator Applying the instanceof operator with a variable the have null value Downcasting with instanceof operator Downcasting without instanceof operator
The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false.
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be reffered by either Dog or Animal class.
class Dog extends Animal{//Dog inherits Animal public static void main(String args[]){ Dog d=new Dog(); System.out.println(d instanceof Animal);//true } } Output:true
} } public static void main (String [] args) { Animal a=new Dog(); Dog.method(a); } } Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is fine. But what will happen if we write:
Animal a=new Animal(); Dog.method(a); //Now ClassCastException but not in case of instanceof operator
class Call{ void invoke(Printable p){//upcasting if(p instanceof A){ A a=(A)p;//Downcasting a.a(); } if(p instanceof B){ B b=(B)p;//Downcasting b.b(); } } }//end of Call class class Test{ public static void main(String args[]){ Printable p=new B(); Call c=new Call(); c.invoke(p); } }
Package
1. Package 2. Example of package 3. Accessing package 1. By import packagename.* 2. By import packagename.classname 3. By fully qualified name 4. Subpackage 5. Sending class file to another directory 6. -classpath switch 7. 4 ways to load the class file or jar file 8. How to put two public class in a package 9. Static Import 10. Package class A package is a group of similar types of classs, interfaces and sub-packages. Package 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. In this page, we will have the detailed learning of creating user-defined packages.
Advantage of Package
Package is used to categorize the classes and interfaces so that they can be easily maintained. Package provids access protection. Package removes naming collision.
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
If you import package.classname then only declared class of this package will be accessible but not subpackages.
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
Note: Sequence of the program must be package then import then class.
Subpackage
Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
package com.javatpoint.core; class Simple{ public static void main(String args[]){ System.out.println("Hello subpackage"); } }
Note: If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
//save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides. e:\sources> set classpath=c:\classes;.; e:\sources> java mypack.Simple
Temporary o By setting the classpath in the command prompt o By -classpath switch Permanent o By setting the classpath in the environment variables o By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public class name.
//save as C.java otherwise Compilte Time Error class A{} class B{} public class C{}
Access Modifiers
1. 2. 3. 4. 5. 6. private access modifier Role of private constructor default access modifier protected access modifier public access modifier Applying access modifer with method overriding
There are two types of modifiers access modifier and non-access modifier. The access modifiers specifies accessibility (scope) of a datamember, method, constructor or class. There are 4 types of access modifiers: 1. 2. 3. 4. private default protected public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
2) default
If you don't use any modifier, it is treated as default modifier bydefault. The default modifier is
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package by only through inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } } Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.
} }
The default modifier is more restrictive than protected. That is why there is compile time error.
Encapsulation
Encapsulation is a process of wrapping code and data together into a single unit. It is a way to achieve data hiding.
Simple example:
//save as Student.java package mypack; public class student{ private string name; public String getName(){ return name; } public void setName(String name){ this.name=name } } package mypack; class Test public static void main(){ Student s=new Student(); s.setname("vijay"); System.out.println(s.getName()); } }
download the example of object cloning As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.
Object class
The Object class is the super class of all the classes in java. The Object is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting. The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.
Array in Java
Normally, array is a collection of similar type of elements that have contigious memory location. In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed elements in an array.
Advantage of Array
Code Optimization: It makes the code optimized, we can retrive or sort the data easily. Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }} Output:10 20 70 40 50
static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5}; min(a);//passing array in the method }} Output:3
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }} Output:1 2 3 2 4 5 4 4 5
Copying an array
We can copy an array to another by the arraycopy method of System class.
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile. On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the classes.
compile by > javac A.java run by > java A sonoo jaiswal 1 3 abc Output: sonoo jaiswal 1 3 abc