Unit-2_Java
Unit-2_Java
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
Default Y Y N N
Public Y Y Y Y
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are created
to use the attributes and methods of a class. 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 the 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.
4. Deserialization
De-serialization is a technique of reading an object from the saved state in a
file. Refer to Serialization/De-Serialization in Java
Example:
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
Syntax: <class_name>(){}
Example:
Unit 2. Classes and Objects
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
2. Parameterized constructor
There is no copy constructor in Java. However, we can copy the values from one
object to another like copy constructor in C++.
• By providing only a setter or getter method, you can make the class read
only or write-only. In other words, you can skip the getter or setter
methods.
• It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the negative
numbers in the setter methods.
• It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
• The encapsulate class is easy to test. So, it is better for unit testing.
//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter
methods. class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {
return acc_no;
}
The human body has different organs. Every organ has a different function to
perform; the heart is responsible for blood flow, the lungs for breathing, the
brain for cognitive activity, and the kidneys for excretion. So we have a
standard method function that performs differently depending upon the organ
of the body.
}
Unit 2. Classes and Objects
class Main {
myShape.area();
myTriangle.area();
myShape.area();
Unit 2. Classes and Objects
myCircle.area();
Output:
The formula for the area of the Triangle is ½ * base * height The formula for
the area of the Circle is 3.14 * radius * radius
class Shape {
System.out.println("Drawing a shape");
@Override
System.out.println("Drawing a circle");
}
Unit 2. Classes and Objects
class Square extends Shape {
@Override
System.out.println("Drawing a square");
class Main {
In this example, we have a base class Shape with a single method draw() that
prints “Drawing a shape” to the console. We then create two subclasses, Circle
and Square, that override the draw() method to print “Drawing a circle” and
“Drawing a square” respectively.
In the main method, we create two instances of the Shape class, s1 and s2,
which are actually instances of the Circle and Square subclasses. When we call
the draw() method on these objects, the correct implementation is called
Unit 2. Classes and Objects
based on the actual type of the object, this is run-time polymorphism. The
program will output: “Drawing a circle” and “Drawing a square”
In this example, the draw() method is overridden in the subclasses, and this
allows for the program to determine which method to use at runtime. This is
known as runtime polymorphism or dynamic polymorphism, Because at
runtime the JVM determines the actual type of the object and calls the
corresponding method.
Types of Polymorphism
1. Method Overloading
2. Method Overriding
3.
What is Method Overloading in Java?
Method overloading is the process that can create multiple methods of the
same name in the same class, and all the methods work in different ways.
Method overloading occurs when there is more than one method of the same
name in the class.
class Shapes {
}
Unit 2. Classes and Objects
System.out.println("Triangle area="+0.5*b*h);
System.out.println("Rectangle area="+l*b);
class Main {
myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);
Unit 2. Classes and Objects
}
Output:
Method overriding is the process when the subclass or a child class has the
same method as declared in the parent class.
class Vehicle{
//defining a method
obj.run();//calling method
Output:
1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism
Method Overloading is when a class has multiple methods with the same
name, but the number, types, and order of parameters and the return type of
the methods are different. Java allows the user freedom to use the same name
for various functions as long as it can distinguish between them by the type
and number of parameters. Check out some of the important questions on run
time polymorphism in java interview questions.
Method Overriding is done when a child or a subclass has a method with the
same name, parameters, and return type as the parent or the superclass; then
that function overrides the function in the superclass. In simpler terms, if the
subclass provides its definition to a method already present in the superclass;
then that function in the base class is said to be overridden.
Upcasting takes place when the Parent class’s reference variable refers to the
object of the child class. For example:
class A{}
Example 1:
In this example, we are creating one superclass Animal and three subclasses,
Herbivores, Carnivores, and Omnivores. Subclasses extend the superclass and
override its eat() method. We will call the eat() method by the reference
variable of Parent class, i.e. Animal class. As it refers to the base class object
and the base class method overrides the superclass method; the base class
method is invoked at runtime. As Java Virtual Machine or the JVM and not the
compiler determines method invocation, it is, therefore, runtime
polymorphism.
Unit 2. Classes and Objects
class Animal{
void eat(){
System.out.println("Animals Eat");
void eat(){
void eat(){
void eat(){
}
Unit 2. Classes and Objects
}
class main{
A.eat();
h.eat();
o.eat();
c.eat();
Output:
Animals eat Herbivores Eat Plants Omnivores Eat Plants and meat
Carnivores eat meat
Inheritance
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
The most common use of this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute
is shadowed by a method or constructor parameter).
super keyword
• The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword
o super can be used to refer immediate parent class instance variable.
o super can be used to invoke immediate parent class method. o
super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable. We can use
super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal
class }
}
class TestSuper1{
Unit 2. Classes and Objects
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
static block
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class. o A
static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value
of it.
class Calculate{
static int cube(int x){
return x*x*x;
}
static class
A class can be declared static only if it is a nested class. It does not require any
reference of the outer class. The property of the static class is that it does not
allows us to access the non-static members of the outer class.
public class JavaStaticClassExample
{
private static String s= "Javatpoint";
2.7 Interfaces:
What is an Interface?
An interface is just like Java Class, but it only has static constants and abstract
method. Java uses Interface to implement multiple inheritance. A Java class
can implement multiple Java Interfaces. All methods in an interface are
implicitly public and abstract.
Syntax for Declaring Interface
interface {
//methods
}
To use an interface in your class, append the keyword "implements" after your
class name followed by the interface name.
class Dog implements Pet
Unit 2. Classes and Objects
interface RidableAnimal extends Animal, Vehicle
p.test();
}
}
Step 2) Save , Compile & Run the code. Observe the Output.
Difference between Class and Interface