JAVA FILE New1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

Classes and Objects in Java

Classes and Objects are basic concepts of Object Oriented Programming which revolve
around the real life entities.
Class
A class is a user defined blueprint or prototype from which objects are created.  It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access .
2. Class name: The name should begin with a initial letter .
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state
of the class and its objects, and methods are used to implement the behavior of the class and
its objects
Object

It is a basic unit of Object Oriented Programming and represents the real life entities.  A
typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with
other objects.
Example of an object : dog.

Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, “menu”. An online shopping system might have
objects such as “shopping cart”, “customer”, and “product”.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e.the
state are unique for each object. A single class may have any number of instances.
Example :

As we declare variables like (type name;). This notifies the compiler that we will use name
to refer to data whose type is type. With a primitive variable, this declaration also reserves
the proper amount of memory for the variable. So for reference variable, type must be
strictly a concrete class name. In general,we can’t create objects of an abstract class or an
interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an
object is actually created and assigned to it. Simply declaring a reference variable does not
create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory.
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}

// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output
Hi my name is tuffy.
My breed ,age, color are papillon, 5, white
 
 This class contains a single constructor. We can recognize a constructor because its
declaration uses the same name as the class and it has no return type. The Java compiler
differentiates the constructors based on the number and the type of the arguments. The
constructor in the Dog class takes four arguments. The following statement provides
“tuffy”,”papillon”,5,”white” as values for those arguments:
 Dog tuffy = new Dog (“tuffy”, “papillon”,5,”white”);
The result of executing this statement can be illustrated as :

Note : All classes have at least one constructor. If a class does not explicitly declare any,
the Java compiler automatically provides a no-argument constructor, also called the
default constructor. This default constructor calls the class parent’s no-argument
constructor (as it contain only one statement i.esuper();), or the Object class constructor if
the class has no other parent (as Object class is parent of all classes either directly or
indirectly).

Ways to create object of a class


There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
Using new keyword : It is the most common and general way to create object in
java. Example:

// creating object of class Test


Test t = new Test();

Using Class.forName(String className) method : There is a pre-defined class in


java.lang package with name Class. The forName(String className) method returns the
Class object associated with the class with the given string name.We have to give the
fully qualified name for a class. On calling new Instance() method on this Class object
returns new instance of the class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

Using clone() method: clone() method is present in Object class. It creates and returns a
copy of the object.

// creating object of class Test


Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();

Deserialization : De-serialization is technique of reading an object from the saved state


in a file. Refer Serialization/De-Serialization in java

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = newObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)


In real-time, we need different objects of a class in different methods. Creating a number
of references for storing them is not a good practice and therefore we declare a static
reference variable and use it whenever required. In this case,wastage of memory is less.
The objects that are not referenced anymore will be destroyed by Garbage Collector of
java. Example:

Test test = new Test();


test = new Test();
In inheritance system, we use parent class reference variable to store a sub-class object. In
this case, we can switch into different subclass objects using same referenced variable.
Example:
class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{
// using Dog object
Animal obj = new Dog();

// using Cat object


obj = new Cat();
}

Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored in a reference
variable.
 They are used for immediate method calling.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are
used to perform some action on capturing an event(eg a key press).
 In example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.
btn.set
OnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
Passing and Returning Objects in Java

Although Java is strictly pass by value, the precise effect differs between whether a primitive
type or a reference type is passed.
When we pass a primitive type to a method, it is passed by value. But when we pass an
object to a method, the situation changes dramatically, because objects are passed by what is
effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between
pass-by-value and pass-by-reference. Basically, a parameter cannot be changed by the
function, but the function can ask the parameter to change itself via calling some method
within it.
 While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
 This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
 Changes to the object inside the method do reflect in the object used as an argument.
In Java we can pass objects to methods. For example, consider the following program :
// Java program to demonstrate objects
// passing to methods.
classObjectPassDemo
{
    inta, b;
  
    ObjectPassDemo(inti, intj)
    {
        a = i;
        b = j;
    }
  
    // return true if o is equal to the invoking
    // object notice an object is passed as an
    // argument to method
    booleanequalTo(ObjectPassDemo o)
    {
        return(o.a == a &&o.b == b);
    }
}
  
// Driver class
publicclassTest
{
    publicstaticvoidmain(String args[])
    {
        ObjectPassDemo ob1 = newObjectPassDemo(100, 22);
        ObjectPassDemo ob2 = newObjectPassDemo(100, 22);
        ObjectPassDemo ob3 = newObjectPassDemo(-1, -1);
  
        System.out.println("ob1 == ob2: "+ ob1.equalTo(ob2));
        System.out.println("ob1 == ob3: "+ ob1.equalTo(ob3));
    }
Output:
ob1 == ob2: true
ob1 == ob3: false
Illustrative images for the above program

Three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:


ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

 From the method side, a reference of type Foo with a name a is declared and it’s
initially assigned to null.
booleanequalTo(ObjectPassDemo o);

 As we call the method equalTo, the reference ‘o’ will be assigned to the object which
is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
 Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’.
Since values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so
boolean true will be return.
if(o.a == a &&o.b == b)
 Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

 Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’.
Since values of ‘a’ and ‘b’ are not same for both the references, so if(condition) is false,
so else block will execute and false will be return.

Defining a constructor that takes an object of its class as a parameter


One of the most common uses of object parameters involves constructors. Frequently, in
practice, there is need to construct a new object so that it is initially the same as some
existing object. To do this, either we can use Object.clone() method or define a constructor
that takes an object of its class as a parameter. The second option is illustrated in below
example:
// Java program to demonstrate one object to
// initialize another
classBox
{
    doublewidth, height, depth;
  
    // Notice this constructor. It takes an
    // object of type Box. This constructor use
    // one object to initialize another
    Box(Box ob)
    {
        width = ob.width;
        height = ob.height;
        depth = ob.depth;
    }
  
    // constructor used when all dimensions
    // specified
    Box(doublew, doubleh, doubled)
    {
        width = w;
        height = h;
        depth = d;
    }
  
    // compute and return volume
    doublevolume()
    {
        returnwidth * height * depth;
    }
}
  
// driver class
publicclassTest
{
    publicstaticvoidmain(String args[])
    {
        // creating a box with all dimensions specified
        Box mybox = newBox(10, 20, 15);
  
        //  creating a copy of mybox
        Box myclone = newBox(mybox);
  
        doublevol;
  
        // get volume of mybox
        vol = mybox.volume();
        System.out.println("Volume of mybox is "+ vol);
  
        // get volume of myclone
        vol = myclone.volume();
        System.out.println("Volume of myclone is "+ vol);
    }
}
Output:
Volume of mybox is 3000.0
Volume of myclone is 3000.0

Returning Objects
In java, a method can return any type of data, including objects. For example, in the
following program, the incrByTen( ) method returns an object in which the value of a (an
integer variable) is ten greater than it is in the invoking object
// Java program to demonstrate returning
// of objects
classObjectReturnDemo
{
    inta;
  
    ObjectReturnDemo(inti)
    {
        a = i;
    }
  
    // This method returns an object
    ObjectReturnDemoincrByTen()
    {
        ObjectReturnDemo temp =
               newObjectReturnDemo(a+10);
        returntemp;
    }
}
  
// Driver class
publicclassTest
{
    publicstaticvoidmain(String args[])
    {
        ObjectReturnDemo ob1 = newObjectReturnDemo(2);
        ObjectReturnDemo ob2;
  
        ob2 = ob1.incrByTen();
  
        System.out.println("ob1.a: "+ ob1.a);
        System.out.println("ob2.a: "+ ob2.a);
    }
}
Output:
ob1.a: 2
ob2.a: 12
Note : When an object reference is passed to a method, the reference itself is passed by use
of call-by-value. However, since the value being passed refers to an object, the copy of that
value will still refer to the same object that its corresponding argument does. That’s why we
said that java is strictly pass-by-value.

Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:
 Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
 Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
class Super{

}
Class Sub extends Super{

}
How to use inheritance in Java
 The keyword used for inheritance is extends.
Syntax :
class derived_class extends base-class
{
//methods and fields
}
In practice, inheritance and polymorphism are used together in java to achieve fast
performance and readability of code.
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
 It is used to differentiate the members of superclass from the members of subclass,
if they have same names.
 It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword
as shown below.
Super.variable
Super.method();
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class.
However, a class can implement one or more interfaces, which has helped Java get rid of
the impossibility of multiple inheritance. 

Important facts about inheritance in Java


 Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.
 Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.
 Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
 Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protectedmethods(like getters and
setters) for accessing its private fields, these can also be used by the subclass.

Access Modifiers in Java


As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor , variable , method or data member. There are four types of access modifiers
available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default: When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default. 
 The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
In this example, we will create two packages and the classes in the packages will be having
the default access modifiers and we will try to access a class from one package from a class
of second package.
2. Private: The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the
class in which they are declared.
 Any other class of same package will not be able to access these members.
 Top level Classes or interface can not be declared as private because
1. private means “only visible within the enclosing class”.
2. protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, they apply only to nested
classes and not on top level classes.
3.Protected: The protected access modifier is specified using the keyword protected.
 The methods or data members declared as protected are accessible within same
package or sub classes in different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from class
A and this protected method is then accessed by creating an object of class B.
4.Public: The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods or data members which are declared as public are accessible from
every where in the program. There is no restriction on the scope of a public data
members.

Important Points:
 If other programmers use your class, try to use the most restrictive access level
that makes sense for a particular member. Use private unless you have a good reason
not to.
 Avoid public fields except for constants.

Super Keyword in Java with inheritance:


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. It is majorly
used in the following contexts:

1. Use of super with variables: This scenario occurs when a derived class and base class
has same data members. In that case there is a possibility of ambiguity for the JVM. We can
understand it more clearly using this code snippet:
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output:
Maximum speed: 20
In the above example, both base class and subclass have a member maxSpeed. We could
access maxSpeed of base class in subclass using super keyword.
 2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we
use super keyword. This code snippet helps to understand the said usage of super keyword.
*/Base class Person */
classPerson
{
    voidmessage()
    {
        System.out.println("This is person class");
    }
}
  
/* Subclass Student */
classStudent extendsPerson
{
    voidmessage()
    {
        System.out.println("This is student class");
    }
  
    // Note that display() is only in Student class
    voiddisplay()
    {
        // will invoke or call current class message() method
        message();
  
        // will invoke or call parent class message() method
        super.message();
    }
}
  
/* Driver program to test */
classTest
{
    publicstaticvoidmain(String args[])
    {
        Student s = newStudent();
  
        // calling display() of Student
        s.display();
    }
}
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message () then, the current
class message () is invoked but with the use of super keyword, message() of superclass could
also be invoked.
3. Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, ‘’super’ can call both parametric as well
as non parametric constructors depending upon the situation. Following is the code snippet
to explain the above concept:
/* superclass Person */
classPerson
{
    Person()
    {
        System.out.println("Person class Constructor");
    }
}
  
/* subclass Student extending the Person class */
classStudent extendsPerson
{
    Student()
    {
        // invoke or call parent class constructor
        super();
  
        System.out.println("Student class Constructor");
    }
}
  
/* Driver program to test*/
classTest
{
    publicstaticvoidmain(String[] args)
    {
        Student s = newStudent();
    }
}
Output:
Person class Constructor
Student class Constructor
Final keyword 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. Following are different contexts
where final is used.

Final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be
extended (inherited). There are two uses of a final class:
1. One is definitely to prevent inheritance, as final classes cannot be extended. For
example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend
them.
2. final class A
3. {
4. // methods and fields
5. }
6. // The following class is illegal.
7. class B extends A
8. {
9. // COMPILE-ERROR! Can't subclass A
10. }
The other use of final with classes is to create an immutable class like the
predefined Stringclass.Youcan not make a class immutable without making it final.

Using final with inheritance :During inheritance, we must declare methods with final
keyword for which we required to follow the same implementation throughout all the
derived classes. Note that it is not necessary to declare final methods in the initial stage of
inheritance(base class always). We can declare final method in any subclass for which we
want that if any other class extends this subclass, then it must follow same implementation of
the method as in the that subclass.

// Java program to illustrate


// use of final with inheritance
  
// base class
abstractclassShape
{
    privatedoublewidth;
      
    privatedoubleheight;
      
    // Shape class parameterized constructor
    publicShape(doublewidth, doubleheight)
    {
        this.width = width;
        this.height = height;
    }
      
    // getWidth method is declared as final
    // so any class extending 
    // Shape cann't override it 
    publicfinaldoublegetWidth()
    {
        returnwidth;
    }
      
    // getHeight method is declared as final
    // so any class extending Shape 
    // can not override it 
    publicfinaldoublegetHeight() 
    {
        returnheight;
    }
  
  
    // method getArea() declared abstract because
    // it upon its subclasses to provide 
    // complete implementation 
    abstractdoublegetArea();
}
  
// derived class one
classRectangle extendsShape
{
    // Rectangle class parameterized constructor
    publicRectangle(doublewidth, doubleheight)
    {
        // calling Shape class constructor
        super(width, height);
    }
  
    // getArea method is overridden and declared 
    // as final so any class extending 
    // Rectangle cann't override it
    @Override
    finaldoublegetArea() 
    {
        returnthis.getHeight() * this.getWidth();
    }
      
}
  
//derived class two
classSquare extendsShape
{
    // Rectangle class parameterized constructor
    publicSquare(doubleside)
    {
        // calling Shape class constructor
        super(side, side);
    }
  
    // getArea method is overridden and declared as 
    // final so any class extending
    // Square cann't override it
    @Override
    finaldoublegetArea() 
    {
        returnthis.getHeight() * this.getWidth();
    }
      
}
  
// Driver class 
publicclassTest
{
    publicstaticvoidmain(String[] args)
    {
        // creating Rectangle object
        Shape s1 = newRectangle(10, 20);
          
        // creating Square object
        Shape s2 = newSquare(10);
          
        // getting width and height of s1
        System.out.println("width of s1 : "+ s1.getWidth());
        System.out.println("height of s1 : "+ s1.getHeight());
          
        // getting width and height of s2
        System.out.println("width of s2 : "+ s2.getWidth());
        System.out.println("height of s2 : "+ s2.getHeight());
          
        //getting area of s1
        System.out.println("area of s1 : "+ s1.getArea());
          
        //getting area of s2
        System.out.println("area of s2 : "+ s2.getArea());
          
    }
}
Output:
width of s1 : 10.0
height of s1 : 20.0
width of s2 : 10.0
height of s2 : 10.0
area of s1 : 200.0
area of s2 : 100.0

Overloading methods in Java:


Overloading allows different methods to have the same name, but different signatures where
the signature can differ by the number of input parameters or type of input parameters or
both. Overloading is related to compile time (or static) polymorphism.

// Java program to demonstrate working of method


// overloading in Java.
  
publicclassSum {
  
    // Overloaded sum(). This sum takes two int parameters
    publicintsum(intx, inty)
    {
        return(x + y);
    }
  
    // Overloaded sum(). This sum takes three int parameters
    publicintsum(intx, inty, intz)
    {
        return(x + y + z);
    }
  
    // Overloaded sum(). This sum takes two double parameters
    publicdoublesum(doublex, doubley)
    {
        return(x + y);
    }
  
    // Driver code
    publicstaticvoidmain(String args[])
    {
        Sum s = newSum();
        System.out.println(s.sum(10, 20));
        System.out.println(s.sum(10, 20, 30));
        System.out.println(s.sum(10.5, 20.5));
    }
}
Output :
30
60
31.0

Can we overload static methods?


The answer is ‘Yes’. We can have two or more static methods with same name, but
differences in input parameters. For example, consider the following Java program.
Refer this for details.
Can we overload methods that differ only by static keyword?
We cannot overload two methods in Java if they differ only by static keyword (number of
parameters and types of parameters is same). See following Java program for example.
Refer this for details.
Can we overload main() in Java?
Like other static methods, we can overload main() in Java. Refer overloading main() in Java
for more details.

// A Java program with overloaded main()


importjava.io.*;
  
publicclassTest {
  
    // Normal main()
    publicstaticvoidmain(String[] args)
    {
        System.out.println("Hi Geek (from main)");
        Test.main("Geek");
    }
  
    // Overloaded main methods
    publicstaticvoidmain(String arg1)
    {
        System.out.println("Hi, "+ arg1);
        Test.main("Dear Geek", "My Geek");
    }
    publicstaticvoidmain(String arg1, String arg2)
    {
        System.out.println("Hi, "+ arg1 + ", "+ arg2);
    }
}
Output :
Hi Geek (from main)
Hi, Geek
Hi, Dear Geek, My Geek

Overriding methods in Java:


In any object-oriented programming language, Overriding is a feature that allows a subclass
or child class to provide a specific implementation of a method that is already provided by
one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature and same return type (or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.
Method overriding is one of the way by which java achieve Run Time Polymorphism.The
version of a method that is executed will be determined by the object that is used to invoke
it. If an object of a parent class is used to invoke the method, then the version in the parent
class will be executed, but if an object of the subclass is used to invoke the method, then the
version in the child class will be executed.In other words, it is the type of the object being
referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed.

// A Simple Java program to demonstrate 


// method overriding in java
  
// Base Class
classParent
{
    voidshow() { System.out.println("Parent's show()"); }
}
  
// Inherited class
classChild extendsParent
{
    // This method overrides show() of Parent
    @Override
    voidshow() { System.out.println("Child's show()"); }
}
  
// Driver class
classMain
{
    publicstaticvoidmain(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = newParent();
        obj1.show();
  
        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = newChild();
        obj2.show();
    }
}
Output:
Parent's show()
Child's show()
Abstract Classes: 
The class which is having partial implementation (i.e. not all methods present in the class
have method definition). To declare a class abstract, use this general form:
abstract class class-name {
//body of class
}
Due to their partial implementation, we cannot instantiate abstract classes. Any subclass of
an abstract class must either implement all of the abstract methods in the super-class, or be
declared abstract itself.Some of the predefined classes in java are abstract. They depends on
their sub-classes to provide complete implementation. For example, java.lang.Number is a
abstract class. For more on abstract classes, see abstract classes in java
Although abstract classes cannot be used to instantiate objects, they can be used to create
object references, because Java’s approach to run-time polymorphism is implemented
through the use of super-class references. Thus, it must be possible to create a reference to an
abstract class so that it can be used to point to a subclass object.
Extended classes:
Extended classes are those classes which are extended by an existing class; that is, it has the
attributes and methods of the existing class. So extended class is the concept for the
inheritance in which the child class acquire the properties of the parent class. Extended
classes are the child class which define by using the extends keyword.
The keyword used for inheritance is extends.
Syntax :

class derived-class extends base-class


{
//methods and fields
}
This derived class is called extended class.

You might also like