Unit-2 Java
Unit-2 Java
ACCESS MODIFIER :
TYPES OF MODIFIER:
• public
• protected
• private
Public Specifier
{ System.out.println("I am an animal.");
}}
animal.legCount = 4;
animal.display(); } }
OUTPUT
I am an animal.
I have 4 legs.
Private Specifier
• The private members can be accessed only inside the same class.
class Data
}
public class Main
OUTPUT:
Protected Specifier
class Animal {
{ System.out.println("I am an animal"); } }
OUTPUT : I am an animal
Default Specifier:
The default members are accessible within the same package but not
outside the package.
package defaultPackage;
class Logger {
void message()
{ System.out.println("This is a message"); }
Note:-Here, the Logger class has the default access modifier. And the
class is visible to all the classes that belong to
the defaultPackage package.
Data member
• Data members are the data variables and member functions are
the functions used to manipulate these variables and together
these data members and member functions defines the
properties and behavior of the objects in a Class
• Syntax: -
static data type v1, v2, v3 ………. Vn;
Ex: -
static String cname;
static String CapIndia;
Types of Methods: -
we know that each and every method is meant for performing some
operation. In java programming we have two types of methods they
are
Instance methods: -
Syntax: -
Return type method name (list of parameters if any)
{
Block of statements;
}
Static methods:
• Static methods: -
Syntax: -
Static Return type method name (list of parameters if any)
{
Block of statements;
}
3. Each and every static method must be accessed with
respect class name.
Java inner class or nested class is a class that is declared inside the
class or interface.
Additionally, it can access all the members of the outer class, including
private data members and methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
Inheritance in Java
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
Multilevel Inheritance Example
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
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.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent
class.
3. There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
Output:
Vehicle is running
Output:
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Test it Now
Output:
black
white
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.
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.
In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it Now
Output:
eating...
barking...
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 because priority is given to local.
The super keyword can also be used to invoke the parent class
constructor. Let's see a simple example:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now
Output:
animal is created
dog is created
Binding
Types of Binding
Static Binding
Output:
print in baseclass.
print in baseclass.
Dynamic Binding
Output:
print in baseclass.
print in derivedclass.
What is Thread ?
2. we can say the smallest part of the process that allows a program
to operate more efficiently by running multiple tasks
simultaneously.
4. All the tasks are executed without affecting the main program. In
a program or process, all the threads have their own separate
path for execution, so each thread of a process is independent.
2. Lightweight process.
3. Running -> Running means that the thread has control of the
processor, its code is currently being executed and thread will
continue in this state until it get preempted by a higher priority
thread, or until it relinquishes control
Methods
5. sleep (int n ) : This method causes the run time to put the current
thread to sleep for n milliseconds. After n milliseconds have
expired, this thread will become elligible to run again.
6. yield( ) : The yield() method causes the run time to switch the
context from the current thread to the next available runnable
thread. This is one way to ensure that the threads at lower priority
do not get started.
- **Advantages of Multithreading:**
- Example:
```java
myThread.start();
```
- Example:
```java
myThread.start();
```
- **Thread Pool:**
- Example:
```java
```
```java
executor.submit(() -> {
// Task to be executed
});
```
- ```java
thread.start();
```
- **Asynchronous I/O:**
- ```java
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(Paths.get("file.txt"));
long position = 0;
// Handle failure
});
```
- ```java
class Counter {
// Synchronized method
```