Unit 2 Classes
Unit 2 Classes
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!");
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);
// 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
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"); } }
} }