Oops Using Java: By: Gurveen Vaseer

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 91

OOPs USING JAVA

By:
Gurveen Vaseer
Objected Oriented Programming
Concepts

• Classes and Objects


• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Features of Java
• Object Oriented 
• Platform Independent
• Simple
• Secure
• Portable
• Robust
Building Blocks
• JDK - The Java Development Kit (JDK) is a software development
environment used for developing Java applications and applets. It
includes the Java Runtime Environment (JRE), an interpreter/loader
(Java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc) and other tools needed in Java development.

• JRE - JRE stands for “Java Runtime Environment” and may also be


written as “Java RTE.” The Java Runtime Environment provides the
minimum requirements for executing a Java application; it consists
of the Java Virtual Machine (JVM), core classes, and supporting files.

• JVM - Java Virtual machine(JVM) is a very important part of both


JDK and JRE because it is contained or inbuilt in both. Whatever
Java program you run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line by line hence it is
also known as interpreter.
Java Variables
Following are the types of variables in Java −
• Local Variables
• Class Variables (Static Variables)
• Instance Variables (Non-static Variables)
Java Modifiers

• Access Modifiers − default, public ,


protected, private
• Non-access Modifiers − final, abstract,
strictfp
First Java Program
public class MyFirstJavaProgram
{
  /* This is my first java program.
* This will print 'Hello World' as the output
*/
  public static void main(String []args)
{
System.out.println("Hello World");
}
}
Java if-else
public class IfElseExample {  
public static void main(String[] args) {  
    //defining a variable  
    int number=13;  
    //Check if the number is divisible by 2 or not  
    if(number%2==0){  
        System.out.println("even number");  
    }else{  
        System.out.println("odd number");  
    }  
}  
}
Leap year
public class LeapYearExample {    
public static void main(String[] args) {    
    int year=2020;    
    if(((year % 4 ==0) && (year % 100 !
=0)) || (year % 400==0)){  
        System.out.println("LEAP YEAR");  
    }  
    else{  
        System.out.println("COMMON YEAR");  
    }  
}    

Java For loop
public class ForExample {  
public static void main(String[] args) {  
    //Code of Java for loop  
    for(int i=1;i<=10;i++){  
        System.out.println(i);  
    }  
}  
}
public class PyramidExample {  
public static void main(String[] args) {  
for(int i=1;i<=5;i++){  
for(int j=1;j<=i;j++){  
        System.out.print("* ");  
}  
System.out.println();//new line  
}  
}  
}  
Java while
public class WhileExample {  
public static void main(String[] args) {  
    int i=1;  
    while(i<=10){  
        System.out.println(i);  
    i++;  
    }  
}  
}  
Java Do While
public class DoWhileExample {  
public static void main(String[] args) {  
    int i=1;  
    do{  
        System.out.println(i);  
    i++;  
    }while(i<=10);  
}  
}  
Practice question

• Write a program to find grade of a


student:
If marks<50 – Grade C
If marks >60 and <50 – Grade B
If marks >70 and <60 – Grade A
Objects, methods and classes
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="A";
System.out.println(s1.id+" "+s1.name) ;
}
}
public class Student{
String name;
int rollno;
int age;
void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();
student.name = "Ramesh";
student.rollno = 253;
student.age = 25;
student.info(); }}
Assign and print the roll number, phone number
and address of two students having names "Sam"
and "John" respectively by creating two objects
of class 'Student’. Print the details of both using
a method.
Programs with Input
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = myObj.nextLine();
  int age = myObj.nextInt();
double salary = myObj.nextDouble();
  System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
 
Method Overloading
• If a class has multiple methods
having same name but different in
parameters, it is known as Method
Overloading
class DisplayOverloading2
{ public void disp(char c)
{ System.out.println(c); }
public void disp(int c)
{ System.out.println(c ); }
}
 class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
 
Constructors in Java
Constructor is a block of code that initializes the
newly created object. A constructor resembles an
instance method in java but it’s not a method as
it doesn’t have a return type. 
• Default
• Parametrized
Default Constructor
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
 
class NoteBook{
NoteBook(){
System.out.println("Default constructor");
}
public void mymethod()
{
System.out.println("Void method of the class");
}
public static void main(String args[]){
NoteBook obj = new NoteBook();
obj.mymethod();
}
}
 
Parametrized Constructor
public class Employee {
int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id, String name){
this.empId = id;
this.empName = name; }
void info(){
System.out.println("Id: "+empId+" Name: "+empName); }
public static void main(String args[]){
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info(); } }
 
Constructor Overloading
• Constructor overloading is a concept of having
more than one constructor with different
parameters list, in such a way so that each
constructor performs a different task. 
Use of this keyword
class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display()
{System.out.println(rollno+" "+name+" "+fee);}
  
}  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  }}  
 
 
class A{  
A(){System.out.println("hello a");}  
A(int x){  
this();  
System.out.println(x);  
}  
}  
class TestThis5{  
public static void main(String args[]){  
A a=new A(10);  
}}  
Static in java
The static keyword in Java is used for
memory management mainly. We can apply
static keyword with variables, methods, blocks
and nested classes. The static keyword belongs
to the class than an instance of the class.
The static can be:
1.Variable (also known as a class variable)
2.Method (also known as a class method)
3.Block
4.Nested class
class Student{  
   int rollno;//instance variable  
   String name;  
   static String college =“OPJU";//static variable  
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
void display (){System.out.println(rollno+" "+name+" "+college);}  
}  
class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(111,“X");  
 Student s2 = new Student(222,“Y");  
 s1.display();  
 s2.display();  
 }  
}  
class Student{  
     int rollno;  
     String name;  
     static String college = “OPJU";  
    
     static void change(){  
     college = “OPJIT";  
     }  
     Student(int r, String n){  
     rollno = r;  
     name = n;  
     }  
     //method to display values  
     void display(){System.out.println(rollno+" "+name+" "+college);}  
}  
 class TestStaticMethod{  
    public static void main(String args[]){  
    Student.change();//calling change method  
    Student s1 = new Student(111,“X");  
    Student s2 = new Student(222,“Y");  
    Student s3 = new Student(333,“Z");  
    //calling display method  
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}  
Inheritance

• Inheritance in Java is a
mechanism in which one object
acquires all the properties and
behaviors of a parent object. 
• Class: A class is a group of objects which have
common properties. It is a template or blueprint
from which objects are created.
• Sub Class/Child Class: Subclass is a class which
inherits the other class. It is also called a derived
class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class
from where a subclass inherits the features. It is
also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a
mechanism which facilitates 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.
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.bo
nus);  
}  
}  
Method OVERRIDING

If subclass (child class) has the same


method as declared in the parent
class, it is known as method
overriding in Java.
In other words, If a subclass provides
the specific implementation of the
method that has been declared by one
of its parent class, it is known as
method overriding.
• Create a class 'Robot' with 3 public member functions:
• start()                that prints "robot started"
• work()                that prints "robot working"
• stop()                 that prints "robot stopped"

• create another class  'DisposalRobot' inherits 'Robot' :


• public findWaste()    print "finding waste"  // new method

Override work function to print "disposing waste"


class Robot
{ void start()
{ System.out.println("Robot started");}
void work()
{ System.out.println("Robot working"); }
void stop()
{ System.out.println("Robot Stopped"); }}
class DisposalRobot extends Robot
{ void findwaste()
{ System.out.println("Finding waste");}
void work()
{ System.out.println("Disposing waste");} }
class main1
{ public static void main(String[] args) {
Robot ob1=new Robot();
DisposalRobot ob2=new DisposalRobot();
ob1.start();
ob1.work();
ob1.stop();
ob2.findwaste(); } }
Types of Inheritance
Single Inheritance
class Employee
{
float sal=60000;
}
class Main extends Employee
{
float b=1500;
float temp= sal + b;
public static void main(String args[])
{
Main ob=new Main();
System.out.println("Salary amount is:"+ob.sal);
System.out.println(" Extra Bonous is:"+ob.temp);
}
}
Multi level inheritance
• class Electronics {
public Electronics(){
System.out.println("Class Electronics");
}
public void deviceType() {
System.out.println("Device Type: Electronics");}}
class Television extends Electronics {
public Television() {
System.out.println("Class Television");
}
public void category() {
System.out.println("Category - Television");}}
class LED extends Television {
public LED() {
System.out.println("Class LED");
}
public void display_tech() {
System.out.println("Display Technology- LED");}}
public class Tester {
public static void main(String[] arguments) {
LED led = new LED();
led.deviceType();
led.category();
led.display_tech();
}
}
Hierarchical Inheritance
• class Employee{
float salary = 40000;}
class PermanentEmp extends Employee{
double hike = 0.5;}
class TemporaryEmp extends Employee{
double hike = 0.35;}
public class HerInheritanceDemo
{
public static void main(String args[]){
PermanentEmp p = new PermanentEmp();
TemporaryEmp t = new TemporaryEmp();
System.out.println("Permanent Employee salary is :"
+p.salary);
System.out.println("Hike for Permanent Employee is:"
+p.hike);
System.out.println("Temporary Employee salary is :"
+t.salary);
System.out.println("Hike for Temporary Employee is :"
+t.hike);}}
super in java
• The super keyword in java is a reference
variable that is used to refer parent class
objects. The keyword “super” came into the
picture with the concept of Inheritance.
Basically this form of super is used to
initialize superclass variables when there is no
constructor present in superclass. On the other
hand, it is generally used to access the specific
variable of a superclass.
class Vehicle {     int maxSpeed = 120; }  
class Car extends Vehicle {     int maxSpeed = 180;
      void display()
    {              System.out.println("Maximum Speed: "
                           + super.maxSpeed);    } }
class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}
 
class Person {
    Person()
    {  
System.out.println("Person class constructor");     } }
 class Student extends Person {
    Student()
    {     super();
System.out.println("Student class Constructor");
    } }
class Test {
    public static void main(String[] args)
    {
        Student s = new Student();     } }
 
final in java
final keyword is used in different contexts. First
of all, final is a non-access
modifier applicable only to a variable, a method
or a class.
Final can be:
1.variable
2.method
3.class
final variable
class Bike9{  
 final int speedlimit=90;
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}
Blank final variable
class Bike10{  
  final int speedlimit;
    
  Bike10(){  
  speedlimit=70;  
  System.out.println(speedlimit);  
  }  
  
  public static void main(String args[]){  
    new Bike10();  
 }  
}  
final method
class Bike{  
  final void run(){System.out.println("running");}  
}  
     
class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  
     
   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  
Polymorphism
Polymorphism is considered as one of the
important features of Object-Oriented
Programming. Polymorphism allows us to perform
a single action in different ways. In other words,
polymorphism allows you to define one interface
and have multiple implementations. The word
“poly” means many and “morphs” means forms, So
it means many forms.
In Java polymorphism is mainly divided into
two types:
• Compile time Polymorphism
• Runtime Polymorphism
• 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.
class Bike{  
  void run(){System.out.println("running");}  
}  
class Splendor extends Bike{  
  void run(){System.out.println("running safely with 60km");}  
  
  public static void main(String args[]){  
    Bike b = new Splendor();//upcasting  
    b.run();  
  }  
}  
class Parent {
void Print()
    {         System.out.println("parent class");    } }
 class subclass1 extends Parent {    void Print()
    {         System.out.println("subclass1");     } }
  class subclass2 extends Parent {
      void Print()
    {        System.out.println("subclass2");     } }
  class TestPolymorphism3 {
    public static void main(String[] args)
    {         Parent a;
          a = new subclass1();
        a.Print();
          a = new subclass2();
        a.Print();     } }
 
• Compile time Polymorphism that is
resolved during compiler time is known
as static polymorphism. Method
overloading is an example of compile
time polymorphism.
Method Overloading: This allows us
to have more than one method having
the same name, if the parameters of
methods are different in number,
sequence and data types of
parameters. 
class SimpleCalculator
{
int add(int a, int b)
{ return a+b; }
int add(int a, int b, int c)
{ return a+b+c; }}
public class Demo
{ public static void main(String args[])
{ SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}}
 
Strings in java
• Java String class provides a lot of
methods to perform operations on
strings such as compare(), concat(),
equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
• The Java String is immutable which
means it cannot be changed.
Whenever we change any string, a
new instance is created.
public class StringExample{  
public static void main(String args[]){  
String s1="java";//
creating string by java string literal  
char ch[]={'s','t','r','i','n','g','s'};  
String s2=new String(ch);//
converting char array to string  
String s3=new String("example");   
System.out.println(s1);  
System.out.println(s2);  
System.out.println(s3);  
}}  
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len ); }}

class Main {
public static void main(String[] args) {
String greet = "Hello! World";
System.out.println("String: " + greet);
 
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length); }}
 
import java.util.Scanner;
class ChkPalindrome
{ public static void main(String args[])
{ String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Exception Handling
• There are mainly two types of
exceptions: checked and unchecked.
1. Checked Exception
2.Unchecked Exception
3.Error
1) Checked Exception
The classes which directly inherit Throwable class
except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known
as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Keyword Description
try The "try" keyword is used to specify a block where we should
place exception code. The try block must be followed by either
catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or
not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an
exception in the method. It is always used with method
signature.
public class TryCatch {  
  
    public static void main(String[] args) {  
        try  
        {  
        int data=50/0; //may throw exception   
        }  
             // handling the exception  
        catch(Exception e)  
        {  
                  // displaying the custom message  
            System.out.println("Can't divided by zero");  
        }  
    }  
      
}  
 
public class TryCatch1 {  
  
    public static void main(String[] args) {  
        try  
        {  
        int arr[]= {1,3,5,7};  
        System.out.println(arr[10]);             

        catch(ArrayIndexOutOfBoundsException e)  
        {  
            System.out.println(e);  
        }  
        System.out.println("rest of the code");  
    }  
      
}  
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}}
 
Multiple catch
public class MultipleCatchBlock3 {  
  
    public static void main(String[] args) {  
          
           try{    
                int a[]=new int[5];    
                a[5]=30/0;    
                System.out.println(a[10]);  
               }    
               catch(ArithmeticException e)  
                  {  
                   System.out.println("Arithmetic Exception occurs");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception occurs");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception occurs");  
                  }             
               System.out.println("rest of the code");    
    }  
}  
public class MultipleCatchBlock4 {  
  
    public static void main(String[] args) {  
          
           try{    
                String s=null;  
                System.out.println(s.length());  
               }    
               catch(ArithmeticException e)  
                  {  
                   System.out.println("Arithmetic Exception occurs");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
                   System.out.println("ArrayIndexOutOfBounds Exception occurs");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception occurs");  
                  }             
               System.out.println("rest of the code");    
    }  
}  
Use of throws
import java.io.*;  
class M{  
 void method()throws IOException{  
  throw new IOException("device error");  
 }  
}  
public class Testthrows2{  
   public static void main(String args[]){  
    try{  
     M m=new M();  
     m.method();  
    }catch(Exception e)
{System.out.println("exception handled");}     
      System.out.println("normal flow...");  
  }  
}
 
Multithreading in Java
• Multithreading in Java is a process of
executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the
smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve
multitasking.
• However, we use multithreading than
multiprocessing because threads use a shared
memory area. They don't allocate separate
memory area so saves memory, and context-
switching between the threads takes less time
than process.
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other
words, each process allocates a separate memory
area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires
some time for saving and loading registers, memory
maps, updating lists, etc.
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
Life cycle of thread
Creating a thread
There are two ways to create a thread:
1.By extending Thread class
2.By implementing Runnable interface.
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...")
;  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}  
class TestSleepMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<5;i++){  
    try
{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();  
   
  t1.start();  
  t2.start();  
 }  
}  
class TestJoinMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<=5;i++){  
   try{  
    Thread.sleep(500);  
   }catch(Exception e){System.out.println(e);}  
  System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
 TestJoinMethod1 t1=new TestJoinMethod1();  
 TestJoinMethod1 t2=new TestJoinMethod1();  
 TestJoinMethod1 t3=new TestJoinMethod1();  
 t1.start();  
 try{  
  t1.join();  
 }catch(Exception e){System.out.println(e);}  
  
 t2.start();  
 t3.start();  
 }  
}  
class TestJoinMethod3 extends Thread{  
  public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestJoinMethod3 t1=new TestJoinMethod3();  
  TestJoinMethod3 t2=new TestJoinMethod3();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());  
  System.out.println("id of t1:"+t1.getId());  
  
  t1.start();  
  t2.start();  
  
  t1.setName(“XY");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
}  
class TestMultiPriority1 extends Thread{  
 public void run(){  
   System.out.println("running thread name is:"+Thread.currentTh
read().getName());  
   System.out.println("running thread priority is:"+Thread.current
Thread().getPriority());  
  
  }  
 public static void main(String args[]){  
  TestMultiPriority1 m1=new TestMultiPriority1();  
  TestMultiPriority1 m2=new TestMultiPriority1();  
  m1.setPriority(Thread.MIN_PRIORITY);  
  m2.setPriority(Thread.MAX_PRIORITY);  
  m1.start();  
  m2.start();  
   
 }  
}
public class TestDaemonThread1 extends Thread{  
 public void run(){  
  if(Thread.currentThread().isDaemon()){
   System.out.println("daemon thread work");  
  }  
  else{  
  System.out.println("user thread work");  
 }  
 }  
 public static void main(String[] args){  
  TestDaemonThread1 t1=new TestDaemonThread1(); 
  TestDaemonThread1 t2=new TestDaemonThread1();  
  TestDaemonThread1 t3=new TestDaemonThread1();  
  
  t1.setDaemon(true);  
    
  t1.start();
  t2.start();  
  t3.start();  
 }  
}  
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.

• There are many ways:


• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.
finalize() method

• The finalize() method is invoked each


time before the object is garbage
collected. This method can be used
to perform cleanup processing. This
method is defined in Object class as:
protected void finalize(){}  
gc() method
• The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime
classes.
public static void gc(){} 
 
public class TestGarbage1{  
 public void finalize()
{System.out.println("object is garbage collected");}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  
Abstract class in java
• A class which is declared as abstract is known as
an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run()
{System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  
Interfaces in Java

• An interface is a reference type in Java. It is similar to


class. It is a collection of abstract methods. A class
implements an interface, thereby inheriting the abstract
methods of the interface.
• Along with abstract methods, an interface may also contain
constants, default methods, static methods, and nested
types. Method bodies exist only for default methods and
static methods.
• Writing an interface is similar to writing a class. But a class
describes the attributes and behaviors of an object. And an
interface contains behaviors that a class implements.
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();  
 }  

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();  
 }  

Packages in Java
• 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.
Example
//save by A.java   //save by B.java  
package pack;   package mypack;  
public class A{   import pack.*;  
  
  public void msg()
class B{  
{System.out.println(
"Hello");}     public static void mai
n(String args[]){  
}  
   A obj = new A();  
   obj.msg();  
  }  
}  

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy