0% found this document useful (0 votes)
4 views

Unit 2 Classes

This document provides an overview of classes in Java, detailing their structure, components, and functionalities such as fields, methods, constructors, and access modifiers. It explains concepts like inheritance, method overloading, and the use of the 'final' keyword, along with examples of object creation and method declaration. Additionally, it covers the importance of reusability and organization in code through inheritance and polymorphism.

Uploaded by

abhaymain9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 2 Classes

This document provides an overview of classes in Java, detailing their structure, components, and functionalities such as fields, methods, constructors, and access modifiers. It explains concepts like inheritance, method overloading, and the use of the 'final' keyword, along with examples of object creation and method declaration. Additionally, it covers the importance of reusability and organization in code through inheritance and polymorphism.

Uploaded by

abhaymain9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Unit-2 - Classes

What is a class in Java?


A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity. It
can't be physical.
A class in Java can contain:
▪ Fields - Java field is a container with associated data.
▪ Methods
▪ Constructors
▪ Blocks
▪ Nested class and interface
Class
1. Class Declaration: A class is declared using the class keyword followed by the class
name.
public class MyClass {
// Class members and methods go here
}
2. Class Members: These are the fields (variables) and methods (functions) defined within
a class. They encapsulate the data and behavior of the objects created from the class.
public class MyClass {
// Field (instance variable)
private int myField;
// Method
public void myMethod() {
// Method body
}
}
Class
3. Access Modifiers: Java provides access modifiers (public, private, protected) to control the
accessibility of class members. These modifiers determine whether a field or method can be
accessed from other classes.
public class MyClass {
private int privateField; // Accessible only within the class
public int publicField; // Accessible from anywhere
protected int protectedField; // Accessible within the same package and subclasses
}
4. Objects: Objects are instances of classes created using the new keyword followed by a
constructor.
MyClass obj = new MyClass(10);
Class
5. Constructors: Constructors are special methods used for initializing objects. They have the same
name as the class and are invoked using the new keyword when creating objects.
public class MyClass {
private int myField;
// Constructor
public MyClass(int initialValue) {
myField = initialValue;
}
}
6. Inheritance: Inheritance is a mechanism where a class (subclass) can inherit properties and behavior from
another class (superclass). It promotes code reuse and allows for creating a hierarchy of classes.

7. Method Overriding: It is a feature that allows a subclass to provide a specific implementation of a


method that is already defined in its superclass.

8. Method Overloading: Method overloading allows a class to have multiple methods with the same name
but different parameters. The method to be called is determined based on the number and type of arguments
passed.
Assigning object reference variables
In Java, assigning object reference variables involves creating variables that can hold references
to objects in memory.
▪ Declare the variable: You start by declaring a variable of a particular type. This type could
be a class that you've defined yourself, or one of the built-in Java classes.
▪ Instantiate an object: Then, you create an object of that type using the new keyword, which
allocates memory for the object.
▪ Assign the object reference: Finally, you assign the reference of the newly created object to
the variable you declared.
Assigning object reference variables
public class MyClass {
public static void main(String[] args) {
// Declare a variable of type String
String myString;
// Instantiate a String object and assign its reference to the variable
myString = new String("Hello, world!");
// Now myString holds a reference to the newly created String object
System.out.println(myString); // Output: Hello, world!
}
} You can also combine declaration and instantiation in a single line:
String myString = new String("Hello, world!");

In the above example:


▪ myString is declared as a variable of type String.
▪ new String("Hello, world!") creates a new String object with the value "Hello, world!".
▪ The reference to this newly created String object is assigned to the variable myString.
Methods
❑ A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
❑ It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again.
❑ It also provides the easy modification and readability of code, just by adding or removing a
chunk of code. The method is executed only when we call or invoke it.
❑ The most important method in Java is the main() method.
Methods
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
❑ Public: The method is accessible by all classes when we use public specifier in our
application.
❑ Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
❑ Protected: When we use protected access specifier, the method is accessible within the same
Methods
❑ Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
❑ Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
❑ Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
❑ Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Methods
Parameters
❑ Actual Parameters
❑ Formal Parameters
Actual Parameters

Formal
Parameters
Method – Example code Example 2
public class Main {
public class Main { Example 1 static void myMethod() {
static void myMethod() { System.out.println("I just got executed!");
System.out.println("I just got executed!"); }
} public static void main(String[] args) {
public static void main(String[] args) { myMethod();
myMethod(); myMethod();
} myMethod();
} }
}
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) { Example 3
myMethod("Liam", 5);
With Parameters
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Method – Object Creation

class Circle
{
double radius;
void calculateArea() //method 1 definition{
double area = 3.14*radius*radius;
System.out.println("Area of circle: " +area); }
void calculateCircumference() //method 2 definition
{
double circum = 2*3.14*radius;
System.out.println("Circumference of circle: " +circum);
}
}
class Main
{
public static void main(String args[])
{
Circle c = new Circle(); //creating object of class circle
c.radius = 5;
c.calculateArea(); //invokes calculateArea() with object c
c.calculateCircumference(); //invokes calculateCircumference() with object c
}
}
Method – Example code
public class Main { public class Main {
static int myMethod(int x) { static int myMethod(int x, int y) {
return 5 + x; return x + y;
} }
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(myMethod(3)); System.out.println(myMethod(5, 3));
} }
} }
// Outputs 8 (5 + 3) // Outputs 8 (5 + 3)
“this”
❑ “this” keyword used for name collisions between Instance variables and formal arguments
❑ Instance variable hiding: When instance variables have the same name as local variables
including formal arguments, local variables hide the Instance variables.
Class Account
{
int a,b;
public void setData(int a, int b)
{
public static void main(String[] args){
this.a=a; Account Obj= new Account()
this.b=b; Obj.setData(5,9)}
return a + b; }
Constructors – “this Keyword”
public class Car {
// Instance variables
private String make;
private String model;
private int year;
// Getter methods
// Constructor with parameters
public String getMake() {
public Car(String make, String model, int year) { return make; }
this.make = make; public String getModel() {
this.model = model; return model; }
this.year = year; } public int getYear() {
return year; }
// Main method for testing
public static void main(String[] args) {
// Creating a new Car object using the constructor
Car myCar = new Car("Toyota", "Camry", 2022);

// Accessing object properties using getter methods


System.out.println("Make: " + myCar.getMake());
System.out.println("Model: " + myCar.getModel());
System.out.println("Year: " + myCar.getYear());
}
}
Method Overloading
❑ Method overloading is a feature of Java in which a class has more than one
method of the same name and their parameters are different.
❑ It can be callable using single object based on their respective parameters.
❑ It is one of the application of Polymorphism.
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Constructors
❑ In Java, a constructor is a block of codes similar to the method.
❑ A constructor has the same name as the class.
❑ class can have more than one constructor.
❑ constructor may take zero, one, or more parameters.
❑ constructor has no return value.
❑ constructor is always called with the new operator.
The constructor is automatically called immediately after the object is created,
before the new operator completes.
Box mybox1 = new Box();
Here Box is class name mybox1 is object
Constructors
class Box // compute and return volume
{ double volume() {
return width * height * depth;
double width; }
double height; }
class BoxDemo7
double depth; {
// This is the constructor for Box. public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box(double w, double h, double d) { Box mybox1 = new Box(10, 20, 15);
width = w; double vol;
// get volume of first box
height = h; vol = mybox1.volume();
depth = d; System.out.println("Volume is " + vol);
}
} } The output from this program is shown here:
Volume is 3000.0
final
In Java, the final keyword is used to define constants, immutable objects, and to
restrict the behavior of classes, methods, and variables.
The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be
• variable
• method
• Class
The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable.
Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
▪ There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
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
}
}//end of class
Java final method
If you make any method as final, you cannot override it.
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(); Output: Compile Time Error
}
}
Java final class
If you make any class as final, you cannot extend it.
final class Bike{
}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
} Output: Compile Time Error
}
Inheritance
❑ Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
❑ 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.
Inheritance
Important terms used in Inheritance
❑ 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.
Importance of Java inheritance
❑Implementation of inheritance in Java provides the following
benefits:
❑Inheritance minimizes the complexity of a code by minimizing
duplicate code.
❑If the same code has to be used by another class, it can simply be
inherited from that class to its sub-class. Hence, the code is better
organized.
❑The efficiency of execution of a code increases as the code is
organized in a simpler form.
❑The concept of polymorphism can be used along with inheritance.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
❑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.
❑In the terminology of Java, a class which is inherited is called a parent
or superclass, and the new class is called child or subclass.
Java Inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{ Output
Programmer salary is:40000.0
int bonus=10000;
Bonus of programmer is: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);
} }
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
❑ Single-level inheritance.
❑ Multi-level Inheritance.
❑ Hierarchical Inheritance.
❑ Multiple Inheritance.
❑ Hybrid Inheritance.
1. Single Inheritance: This is the simplest form of inheritance where a class inherits
from only one superclass. In Java, a class can extend only one other class.
Syntax:
class Superclass {
// Superclass methods and attributes
}
class Subclass extends Superclass {
// Subclass methods and attributes
Single Inheritance

// Parent class
class Animal {
void eat() {
System.out.println("Animal is eating...");
} }
// Child class inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking...");
} }
Single Inheritance
public class Main {
public static void main(String[] args) {
// Creating an instance of Dog
Dog myDog = new Dog();
// Calling methods from both parent and child classes
myDog.eat(); // Method from the parent class
myDog.bark(); // Method from the child class
} }
▪ Animal is the parent class with a method eat().
▪ Dog is the child class which extends Animal and has an additional method
bark().
▪ In the main() method, an instance of Dog is created and methods eat() and bark()
are called on this instance. The eat() method is inherited from the parent class
Animal, while the bark() method is specific to the Dog class.
Multi level Inheritance
► Multilevel inheritance in Java occurs when a class extends another class,
which in turn extends another class, creating a hierarchy of classes.
► Each subclass inherits properties and behaviors from its immediate superclass
and all the way up the inheritance chain.
Multi-level Inheritance
Multi-level
// Parent class
class Animal {
void eat() {
System.out.println("Animal is eating");
}}
// Child class inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}}
// Grandchild class inheriting from Dog
class Labrador extends Dog {
void display() {
System.out.println("Labrador is a type of Dog");
}}
Multi-level Inheritance

public class Main {


public static void main(String[] args) {
Labrador labrador = new Labrador();
labrador.eat(); // Inherited from Animal
labrador.bark(); // Inherited from Dog
labrador.display(); // Defined in Labrador class
}
}
Hierarchical inheritance
► In Java, hierarchical inheritance refers to a situation where one class serves
as a superclass for multiple subclasses.
► Each subclass inherits attributes and methods from the superclass
class Animal {// Superclass
void eat() {
System.out.println("Animal is eating");
} }
class Dog extends Animal {// Subclass 1
void bark() {
System.out.println("Dog is barking");
} }
class Cat extends Animal {// Subclass 2
void meow() {
System.out.println("Cat is meowing");
} }
Hierarchical inheritance
// Main class

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Accessing eat() method from Animal class
dog.bark(); // Accessing bark() method from Dog class
Cat cat = new Cat();
cat.eat(); // Accessing eat() method from Animal class
cat.meow(); // Accessing meow() method from Cat class
}
}
Hybrid Inheritance
❑ Hybrid inheritance in Java occurs when a class inherits properties and behaviors from multiple
classes through a combination of single, multiple, and multilevel inheritance.
❑ This can be achieved by extending one class and implementing one or more interfaces.
class Parent1 { // Parent class 1
// Properties and methods
}
class Parent2 { // Parent class 2
// Properties and methods
}
interface Interface1 {// Interface
// Methods declaration
}
// Child class inheriting from Parent1 and implementing Interface1
class Child extends Parent1 implements Interface1 {
// Properties and methods
}
Hybrid Inheritance // Child class inheriting from Animal and
Vehicle, and implementing Pet interface
// Parent class 1
class Dog extends Animal implements Pet {
class Animal {
public void play() {
void eat() {
System.out.println("Dog is playing");
System.out.println("Animal is eating");
}
}}
}
// Parent class 2
public class Main {
class Vehicle {
public static void main(String[] args) {
void drive() {
Dog dog = new Dog();
System.out.println("Vehicle is driving");
dog.eat(); // Output: Animal is eating
}}
dog.play(); // Output: Dog is playing
// Interface
}
interface Pet {
}
void play();
}
In this example, Dog class inherits eat() method from Animal class, drive() method from
Vehicle class, and implements the play() method from the Pet interface, thus demonstrating
hybrid inheritance in Java.
“Static Variables”
▪ Static variable is shared by all the Objects
▪ Declared with static.
▪ Only one copy exists, shared by all objects of the class.
▪ Static is class member not object member
▪ Useful for constant values (e.g., PI) or counters shared across objects.
class Mobile
{
String brand;
int price;
static String name;
public void show()
{
System.out.println("brand+ ":" +price+":" +name);
}}
“Static Variables”
public class Demo
{
Mobile obj2 = new Mobile();
public static void main(String args[]) obj2.brand="Samsung";
{ obj2.price=1700;
Mobile obj1 = new Mobile(); //Mobile.name="SmartPhone";
obj1.brand="Apple"; Mobile.name = "Phone";
obj1.price=1500; obj1.show();
//Mobile.name="SmartPhone"; obj2.show();
}
Static methods
▪ In Java, a static method is a method that belongs to a class rather than an
instance of a class.
▪ The method is accessible to every instance of a class, but methods defined in
an instance are only able to be accessed by that object of a class.
public class MyClass {
// Static method
public static void myStaticMethod() {
System.out.println("This is a static method");
}
// Non-static method
public void myNonStaticMethod() {
System.out.println("This is a non-static method");
}
Static methods public static void main(String[] args) {
// Calling the static method
► Static methods MyClass.myStaticMethod();
// Creating an object of the class
MyClass obj = new MyClass();
// Calling the non-static method using the object
obj.myNonStaticMethod();
}
}
▪ In the above example, myStaticMethod() is a static method because it is declared with the
static keyword.
▪ We can call this method directly using MyClass.myStaticMethod() without creating an
object of MyClass.
▪ On the other hand, myNonStaticMethod() is a non-static method because it is not declared
with the static keyword.
▪ To call this method, we need to create an object of the class and then call the method using
that object (obj.myNonStaticMethod()).
Using objects as parameters
▪ Using objects as parameters in Java allows you to pass objects as arguments to methods,
enabling you to manipulate and operate on those objects within the method.
▪ This is particularly useful when you want to perform operations on the attributes

class Person { public class Main {


String name; public static void main(String[] args) {
int age; Person john = new Person("John", 30);
public Person(String name, int age) { System.out.println("John's age before
this.name = name; modification: " + john.age); // 30
this.age = age; } john.modifyAge(john); // Pass the reference
public void modifyAge(Person p) { to the modifyAge method
p.age++; // Modify the age of the object System.out.println("John's age after
pointed to by the parameter modification: " + john.age); // 31 (age has been
} } incremented)
} }
Java Inner Classes (Nested Classes)
▪ Java inner class or nested class is a class that is declared inside the class or
interface.
▪ We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
▪ Additionally, it can access all the members of the outer class, including private
data members and methods. Syntax
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Java Inner Classes (Nested Classes)
Advantage of Java inner classes
▪ There are three advantages of inner classes in Java. They are as follows:
▪ Nested classes represent a particular type of relationship that is it can access all
the members (data members and methods) of the outer class, including private.
▪ Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
▪ Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java


An inner class is a part of a nested class. Non-static nested classes are known as inner
classes.
Super Keyword
▪ In Java, the super keyword is used to refer to the immediate parent class of a
subclass.
▪ It can be used to access methods, variables, and constructors of the superclass.
▪ The super keyword is particularly useful when you want to differentiate
between members of a subclass and members of its superclass that have the
same name.
Super Keyword
“Super”

Class Parent{
int a=40;
void display(){
System.out.println("Parent Class"); class ParentChild{
} } public static void main(String args[])
class child extends Parent{ {
int a=30; child obj = new child();
void display(){ obj.display();
System.out.println("Child Class"); }
System.out.println(a); }
System.out.println(super.a);
super.display(); }
}
Super Keyword - Accessing superclass constructor
Accessing superclass constructor: You can use super() to call the constructor of the
superclass from the constructor of the subclass. This is useful when you want to
initialize the superclass's fields before initializing the subclass's fields.
class Superclass {
Superclass() {
// Constructor logic
} }
class Subclass extends Superclass {
Subclass() {
super(); // Call superclass
constructor
// Subclass constructor logic
}
}
Accessing superclass method or field
Accessing superclass method or field: You can use super.method() or super.field to
access the method or field of the superclass from within the subclass. This is useful
when you want to invoke a method or access a field from the superclass that has
been overridden or hidden in the subclass.
class Superclass {
void display() {
System.out.println("Inside superclass");
}
}
class Subclass extends Superclass {
void display() {
super.display(); // Call superclass method
System.out.println("Inside subclass");
}
}
Dynamic method Dispatcher
► Dynamic method dispatch is a mechanism in Java where the method to be
invoked is determined at runtime, based on the type of object on which the
method is called.
► It's an essential feature for achieving runtime polymorphism in object-
oriented programming.
class A{ public class Demo{
public void show(){ public static void main(String args[])
System.out.println("A Show"); {
} } A obj = new A(); //Create obj using Parent class A
class B extends A{ obj.show();
public void show(){ obj = new B(); //Use the same object refer to Class B
System.out.println("B Show"); } } obj.show();
class C extends A{ obj = new C(); //Use the same object refer to Class C
public void show(){ obj.show();
System.out.println("C Show"); } }
} }

You might also like