Core Java (Unit Ii)
Core Java (Unit Ii)
In Java, a class is a blueprint or a template for creating objects (instances) with specific attributes
and behaviors. Here are the steps to declare a class, name a class, define rules for assigning classes
and subclasses, create objects, and find the class of an object:
To declare a class in Java, you use the `class` keyword followed by the class name. Here's a simple
example:
- Class names must start with a letter (A-Z or a-z) or an underscore (_).
- The rest of the class name can contain letters, digits (0-9), and underscores.
- Class names are case-sensitive, meaning "MyClass" and "myclass" are considered different class
names.
In Java, you can create subclasses by extending an existing class. The subclass inherits the fields
and methods of the superclass and can add or modify them. Here's an example of creating a
subclass:
To create an object of a class, you use the `new` keyword, followed by the class constructor. The
constructor initializes the object and returns a reference to it. Here's how you create an object:
To determine the class of an object in Java, you can use the `getClass()` method provided by the
`Object` class, which is the root class for all Java classes. Here's an example:
The `getClass()` method returns a `Class` object representing the class of the object. You can use
the `getName()` method of the `Class` object to get the class name as a string.
2. Data members
In Java programming, when you're working with classes and objects, you'll be declaring data
members (also known as fields or attributes), naming variables, and using class members (methods
and variables). Here's a basic rundown:
Data members are variables that hold data associated with a class. They define the state of an
object. Here's an example of how you declare data members in a class:
- Avoid using reserved words (like `int`, `String`, etc.) as variable names.
int studentAge;
String userName;
final int MAX_VALUE = 100;
You can access data members using the dot (`.`) operator.
Methods are functions defined within a class. You can call methods using the dot (`.`) operator.
// Calling a method
obj.printValues();
}
}
Remember, for a method to be callable, it should be either `static` or you need an instance of the
class to call it.
3. Methods
In Java, using data members, invoking methods, passing arguments to a method, and calling
methods are essential aspects of object-oriented programming. Here's a detailed explanation:
Data members (also known as fields or attributes) are variables declared within a class. They define
the state of an object. To use data members, you first need to create an instance of the class.
Methods are functions defined within a class. They can perform specific actions and may or may not
return a value.
Methods can accept parameters (also known as arguments) which allow you to pass data to the
method for processing.
To call a method, you need an instance of the class (if the method is not `static`). Then, you use the
dot (`.`) operator followed by the method name and any necessary arguments.
// Invoking a method
obj.printValue(20); // Passing an argument to the method
}
}
Here's an example that demonstrates using data members, invoking a method, passing an argument
to a method, and calling the method:
// Invoking a method
obj.printValues(); // This will print both values
}
}
This example creates an instance of `MyClass`, sets values for its data members, and then calls the
`printValues` method which prints the values of `myInt` and `myString`.
In Java, there are access modifiers and keywords that control the visibility and behavior of classes,
methods, and variables. Here's an explanation of the common access modifiers (`default`, `public`,
`private`, `protected`) and the keywords `static` and `final`:
- It allows access to members (classes, methods, and variables) from within the same package but
not from outside the package.
4.2. public
- The `public` access modifier allows access from anywhere, including outside the package.
- It provides the widest scope and is used for classes, methods, and variables that are meant to be
accessible from anywhere in the program.
- The `private` access modifier restricts access to members within the same class.
4.4. protected:
- The `protected` access modifier allows access within the same package and by subclasses (even
if they are in different packages).
- It's often used when you want to provide access to subclasses while limiting access to other
classes outside the package.
4.5. static:
- The `static` keyword is used to create class-level members (methods and variables) that belong
to the class itself, not to instances of the class.
- You can access static members using the class name without creating an object.
4.6. final:
- The `final` keyword is used to make a class, method, or variable unchangeable or unextendable.
- When applied to a variable, it means the variable's value cannot be changed once it's initialized.
5. Overloading
Method overloading and constructor overloading are two important concepts in Java that allow you
to define multiple methods or constructors with the same name in the same class but with different
parameters. The key to method or constructor overloading is that the method or constructor names
are the same, but they differ in the number or types of their parameters.
Method overloading allows you to define multiple methods in the same class with the same name
but different parameter lists. The methods can have different numbers or types of parameters.
In the example above, the `add` method is overloaded with different parameter lists based on the
number and types of parameters. The appropriate method is called based on the arguments
provided.
Constructor overloading is the same concept as method overloading, but it applies to class
constructors. You can have multiple constructors in the same class with the same name but
different parameter lists.
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
In the `Person` class, there are three constructors with different parameter lists. Depending on how
you create an instance of the `Person` class, the appropriate constructor is called to initialize the
object.
6. Java class library
In Java, there are several types of classes that serve different purposes and have specific
characteristics. Some of the common types of classes include:
- Regular classes are used to encapsulate data and behavior, and they can be instantiated to create
objects.
- Abstract classes are used to define a common interface or behavior for a group of related classes.
6.3. Interface:
- An interface is similar to an abstract class but can only define method signatures (no method
implementations) and constants (implicitly `public`, `static`, and `final`).
- Interfaces are used to define contracts for classes that implement them.
6.4. Enum:
- An enum (short for "enumeration") is a special class used to represent a fixed set of constants.
- It's often used to define a list of named values, which are typically treated as symbolic names for
integer values.
- It can access the members of the outer class, and the outer class can access the members of the
inner class.
- Inner classes are used for encapsulation, organizing code, and creating relationships between
classes.
- A static nested class is similar to an inner class, but it doesn't have a reference to an instance of
the outer class.
- It's often used when you want to group related classes together without a tight relationship to
the outer class.
7.1. If-Then-Else:
- The `if-then-else` statement is used for conditional execution. It allows you to execute a block of
code if a certain condition is true, and another block of code if the condition is false.
- The `switch` statement is used for multi-branching based on the value of an expression. It
provides a way to compare a single value with multiple possible values and execute different code
blocks accordingly.
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
// ...
default:
System.out.println("Invalid day");
}
- The ternary conditional operator (`? :`) is a shorthand way to express an `if-then-else` statement
in a single line. It returns one of two values based on a given condition.
- The `while` loop is used for executing a block of code repeatedly as long as a specified condition
is true.
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
- The `do-while` loop is similar to the `while` loop but guarantees that the loop body is executed at
least once before checking the condition.
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
- The for-each loop is used to iterate through collections like arrays and lists without the need for
explicit indexing.
8. Array
In Java, you can create arrays to store collections of elements. There are one-dimensional arrays
(like lists) and two-dimensional arrays (like tables). Here's how you create them:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
You can also initialize an array after declaration, using a loop or by reading values from user input,
for example.
Remember, arrays in Java are zero-indexed, which means the first element is at index 0. The length
of an array is accessed with the `length` property (e.g., `numbers.length`).
9. String
In Java, a string is an object that represents a sequence of characters. It's widely used for storing
and manipulating textual information. Here's how you can work with string arrays and some
common string methods:
1. length():
2. charAt(int index):
- The first version returns from `beginIndex` to the end of the string.
- Returns the index of the first (or last) occurrence of the specified substring.
- Returns a new string with all characters converted to upper or lower case.
- Checks if the string starts with or ends with the specified prefix or suffix.
8. split(String regex):
- Splits the string into an array of substrings based on the given regular expression.
10. Inheritance:
1. Single Inheritance:
- Single inheritance occurs when a class inherits from only one superclass.
- In Java, single inheritance is the default and the only type of class inheritance, as a class can
extend at most one other class.
Example:
class Parent {
// Parent class members
}
- Although Java does not support multiple inheritance for classes (a class cannot extend more than
one class), it allows multiple inheritance of behavior through interfaces.
- A class can implement multiple interfaces, inheriting method signatures from each of them.
Example:
interface A {
void methodA();
}
interface B {
void methodB();
}
It's important to note that Java does not support multiple inheritance of state (fields). If a class
implements multiple interfaces, it only inherits the method signatures from those interfaces, not
the fields or state. This prevents the "diamond problem" and the complexities associated with
multiple inheritance of state that are seen in some other programming languages.
3. Hierarchical Inheritance:
- Hierarchical inheritance occurs when multiple classes inherit from a single superclass.
Example:
class Parent {
// Parent class members
}
4. Multilevel Inheritance:
- Multilevel inheritance occurs when a class inherits from another class, which in turn inherits
from another class, creating a chain or hierarchy of inheritance.
Example:
class Grandparent {
// Grandparent class members
}
- Hybrid inheritance combines two or more types of inheritance. For example, it can include
multiple inheritance of classes and interfaces.
- Java doesn't support hybrid inheritance due to potential complexities and conflicts it may
introduce, such as the "diamond problem."
11. Interfaces
In Java, an interface is a reference type similar to a class, but it only contains method signatures
without implementations. It provides a contract that classes implementing the interface must
adhere to. Here's how you define, extend, and implement interfaces:
interface MyInterface {
void method1();
int method2(String input);
}
In this example, `MyInterface` declares two method signatures: `method1()` and `method2()`.
Classes implementing this interface must provide implementations for these methods.
An interface can extend one or more other interfaces. This is similar to classes extending other
classes, but you use the `extends` keyword.
In this example, `MyClass` implements `MyInterface`. It must provide implementations for both
`method1()` and `method2()`.
Example:
interface MyInterface {
void method1();
int method2(String input);
}
Interfaces provide a way to achieve abstraction and define contracts for classes to follow. They are
widely used in Java for achieving polymorphism and decoupling code.