Chapter – II Class and Object-Lect
Chapter – II Class and Object-Lect
Senior Lecturer
Modifiers Access and Non-Access
Department of Computer Science
Method and constructor
Hawassa University
o Many objects are of the same kind but have different identity.
₋ Class name
}
Dog class definition Example
public class Dog {
₋ This class Dog has 3 methods and instance variables.
private String breed;
₋ Methods like:- barking(), hungry(), sleeping()
private int age
₋ States like:- breed, age, color.
private String color;
void barking() { //body …………………. }
void hungry() {//body ……………………}
void sleeping() {//body ................ }
}
Extended Class Definition
[Accesses Modifier ] <class> <ClassName> [extends] [Superclass]
[implements ] [interface1, Inteface2] {
[Access Modifier] <Data Type> <DataMember1>;
[Access Modifier] <Data Type> <Data Member2 >;
[Access Modifier] <Return Type> <MrthodName1> ( [Para1, Para2 …]) {
//method body
}
[Access Modifier] <ClassName> ([optional Parameter lists]) {
// Constructors Body
}
o An object must be created using the class name and new keyword
3. Initialization- the ‘new’ key word is followed by a constructor call. This call
initializes the new object.
Object Creation Example
Example Create an object of Car
o Access modifiers are keywords used as a prefix with class, method and variables.
₋ Package private
₋ Public
₋ Private
₋ Protected
Package private
₋ Any class member which is defined as public would have an access privilege from
any other class regardless of the package specification
o The third relationship is between a class and its present and future subclasses.
o These subclasses are much closer to a parent class than to any other "outside"
classes for the following reasons:
₋ Subclasses are usually more intimately aware of the internals of a parent class
₋ Subclasses are often written by you or by someone to whom you’ve given your
source code.
o The table below shows each type of modifier, it goes from least
restrictive (public) to most restrictive (private).
Modifier Class Package Subclass Everywhere
public Y Y Y Y
protected Y Y Y N
Package private Y Y N N
private Y N N N
Constructors and Methods
Constructors
o Constructors are a special methods that are used to
initialize the class and instance variables automatically
at the time of object is creation
o Constructors have the same name as the class name.
o No return type is specified for the constructor
o By default, constructors are public
o Constructors can be invoked only during object creation or from
other constructors using this keyword.
Defining constructor
o General Syntax
[public] <ClassName><([parameters]) >{
//body of the constructor
}
Types of Constructor
o Default constructor
₋ If you declare any constructors for a class, the Java compiler will not create a
default constructor for that class.
o The value must passed from the user when the object is created
Constructor: Example
₋ Car carObj = new Car(); this line of statement will invoke the no argument
constructor
public Car(String make, String model, int year, double mpg, String color) {
this(); // this line will invoke the no argument constructor
}
Example
public class Student{ Invoking the
String firstName, lastName, sex;
int age;
paramconstructor using
public Student() { this() method from other
this("Dawit", "Tesfaye", 27, "Male"); constructor
}
public Student(String firstName, String lastName, int age, String sex) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.sex = sex;
} Invoking the no argument
public static void main(String[] args) { constructor when the
Student stud1 = new Student();
} object is created
}
Methods
Method
o A method is a block of code that performs a specific task and can be called
(invoked) when needed. Methods help in:
₋ Organizing code
₋ Reusing code
₋ Making code more readable and maintainable
o Suppose you need to create a program to create a circle and color it. You can
create two methods to solve this problem:
₋ a method to draw the circle
₋ a method to color the circle
Types of Methods
o Types of Methods
₋ Standard Library Methods: These are built-in methods in Java that are
available to use.
o concat(), str1.concat(str2)
o // Integer methods
₋ int num = Integer.parseInt("123"); // String to int
₋ String s = Integer.toString(456); // int to String
₋ int max = Integer.max(10, 20); // Maximum of two numbers
₋ int min = Integer.min(10, 20); // Minimum of two numbers
o // Double methods
₋ double d = Double.parseDouble("3.14"); // String to double
₋ boolean nan = Double.isNaN(d); // Checks if Not-a-Number
Character Methods
o char c = 'A';
₋ boolean isLetter = Character.isLetter(c); // Checks if character is letter
₋ boolean isDigit = Character.isDigit('7'); // Checks if digit
₋ boolean isWhitespace = Character.isWhitespace(' '); // Checks whitespace
₋ char lowerCase = Character.toLowerCase(c); // Converts to lowercase
₋ char upperCase = Character.toUpperCase('a'); // Converts to uppercase
Array Methods
o List<String> list = new ArrayList<>();
₋ list.add("Apple");
₋ list.add("Banana");
₋ Collections.sort(list); // Sorts list
₋ Collections.reverse(list); // Reverses list
₋ Collections.shuffle(list); // Randomly shuffles
₋ int freq = Collections.frequency(list, "Apple"); // Counts frequency
o // List methods
₋ String item = list.get(0); // Gets element by index
₋ list.set(1, "Orange"); // Replaces element
₋ int size = list.size(); // Gets size
User Defined Method : Syntax
o calling Syntax for the None static method inside static method is
objectName.methodName(arguments); // if the method is void
o Calling a none static method inside instance method of the same class and
o Calling a static method in any method of the same class
₋ is possible using its signature without object reference
₋ Syntax : methodName(arguments list..);
o In both the above cases, if the call is from different classes, it is must to
use object reference.
₋ Syntax : objectReference.methodName(arguments list..);
Reading assignment
o Parameter Passing
o Java Garbage collector
o enum (Enumerator)
Destroying Object
o Encapsulation
End of Chapter –II Class and Object
Class and object
Define a class Compiled By: Daniel Tesfay
Hawassa University
Method and constructor 2022
Instantiating an object
CHAPTER III