UNIT 2
Creating a Class and Subclass in Java
Java is an object-oriented programming language where programs are written using
classes and objects.
A class is a blueprint of an object, while a subclass is a class that inherits properties and
methods of another class.
Declaring a Class
A class is declared using the class keyword.
Syntax
class ClassName {
// variables
// methods
}
Example
class Student {
int rollNo;
String name;
void display() {
[Link](rollNo + " " + name);
}
}
Naming a Class
Java follows CamelCase naming convention for class names.
Rules for Naming a Class
Class name should start with a capital letter.
Class name should be a noun.
No spaces are allowed.
Class name should not be a Java keyword.
File name must be same as the public class name.
Examples
✔ Student
✔ BankAccount
✘ student data
✘ class
Subclass in Java
A subclass is a class that inherits another class using the extends keyword.
The existing class is called Superclass / Parent class.
The new class is called Subclass / Child class.
Rules to Assign Class & Subclass (Inheritance Rules)
1. A subclass can access public and protected members of the superclass.
2. Private members of a superclass cannot be accessed directly in the subclass.
3. Java supports single inheritance using classes.
4. A subclass can add new methods and variables.
5. A subclass can override methods of the superclass.
6. The extends keyword is used to create a subclass.
Example: Class and Subclass
Superclass
class Person {
String name;
int age;
void show() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
Subclass
class Student extends Person {
int rollNo;
void display() {
[Link]("Roll No: " + rollNo);
}
}
Main Class
class Main {
public static void main(String[] args) {
Student s = new Student();
[Link] = "Sakshi";
[Link] = 20;
[Link] = 101;
[Link]();
[Link]();
}
}
Output
Name: Sakshi
Age: 20
Roll No: 101
Creating a New Object and Class of an
Object in Java
In Java, objects are created from classes.
A class defines the properties and behavior, while an object is a real-world instance of that
class.
Creating a New Object
An object is created using the new keyword.
Syntax
ClassName objectName = new ClassName();
Explanation
ClassName → Name of the class
objectName → Reference variable
new → Allocates memory at runtime
ClassName() → Constructor call
Class of an Object
Every object in Java belongs to a specific class.
The class of an object can be identified using:
o The class name used during object creation
o The method getClass()
Complete Program Demonstrating Object
Creation and Class of an Object
Program
class Student {
// Instance variables
int rollNo;
String name;
float percentage;
// Method to assign values
void setData(int r, String n, float p) {
rollNo = r;
name = n;
percentage = p;
}
// Method to display student details
void displayData() {
[Link]("Roll Number : " + rollNo);
[Link]("Name : " + name);
[Link]("Percentage : " + percentage);
}
}
public class ObjectDemo {
public static void main(String[] args) {
// Creating first object
Student s1 = new Student();
[Link](101, "Sakshi", 85.5f);
// Creating second object
Student s2 = new Student();
[Link](102, "Aarya", 78.2f);
[Link]("---- Student 1 Details ----");
[Link]();
[Link]();
[Link]("---- Student 2 Details ----");
[Link]();
// Showing class of object
[Link]();
[Link]("Class of s1 object: " + [Link]().getName());
[Link]("Class of s2 object: " + [Link]().getName());
}
}
Output
---- Student 1 Details ----
Roll Number : 101
Name : Sakshi
Percentage : 85.5
---- Student 2 Details ----
Roll Number : 102
Name : Aarya
Percentage : 78.2
Class of s1 object: Student
Class of s2 object: Student
Data Members and Methods in Java
In Java, a class contains data members (variables) and methods (functions).
Data members store data, while methods define the behavior of an object.
1. Data Members
Declaring Data Members
Data members are variables declared inside a class but outside any method.
Syntax
class ClassName {
dataType variableName;
}
Example
class Student {
int rollNo;
String name;
float marks;
}
Naming Variables (Data Members)
Must start with a letter, _ or $
Cannot start with a number
Cannot be a Java keyword
Should be meaningful
Follow camelCase convention
Valid Names:
rollNo, totalMarks, studentName
Invalid Names:
1roll, total marks, class
2. Using Class Members (Data Members)
Data members are accessed using an object reference.
Example
Student s = new Student();
[Link] = 101;
[Link] = "Sakshi";
[Link] = 85.5f;
Methods in Java
A method is a block of code that performs a specific task.
Methods can use data members, accept arguments, and return values.
3. Using Data Members inside Methods
Methods can directly access data members of the same class.
Example
void display() {
[Link](rollNo);
[Link](name);
[Link](marks);
}
4. Invoking a Method
Invoking a method means executing the method using an object.
Syntax
[Link]();
5. Passing Arguments to a Method
Arguments are values passed to a method when it is called.
Example
void setData(int r, String n, float m) {
rollNo = r;
name = n;
marks = m;
}
Here, r, n, and m are parameters.
6. Calling a Method
Calling a method means using the method name with required arguments.
Example
[Link](101, "Sakshi", 85.5f);
[Link]();
Complete Program Demonstrating Data
Members and Methods
class Student {
// Data members
int rollNo;
String name;
float marks;
// Method to assign values (using arguments)
void setData(int r, String n, float m) {
rollNo = r;
name = n;
marks = m;
}
// Method using data members
void displayData() {
[Link]("Roll No : " + rollNo);
[Link]("Name : " + name);
[Link]("Marks : " + marks);
}
}
public class MemberDemo {
public static void main(String[] args) {
// Creating object
Student s1 = new Student();
// Calling method and passing arguments
[Link](101, "Sakshi", 85.5f);
// Invoking method
[Link]();
}
}
Output
Roll No : 101
Name : Sakshi
Marks : 85.5
Java access modifiers
Java access modifiers are used to specify the scope of the variables, data members,
methods, classes, or constructors. These help to restrict and secure the access (or, level of
access) of the data.
There are four different types of access modifiers in Java, we have listed them as follows:
1. Default (No keyword required)
2. Private
3. Protected
4. Public
1)Default Access Modifier
Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
Example of Default Access Specifier
Class with Default Members (Same Package)
class Demo { // default class
int x = 10; // default data member
void show() { // default method
[Link]("Value of x: " + x);
}
}
Main Class in Same Package
class DefaultTest {
public static void main(String[] args) {
Demo d = new Demo();
[Link](); // accessible
}
}
Output
Value of x: 10
Private Access Modifier:
Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
Variables that are declared private can be accessed outside the class, if public getter
methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and
hides data from the outside world.
Example:
class Student {
private int marks = 85; // private data member
private void showMarks() { // private method
[Link]("Marks: " + marks);
}
// public method to access private members
public void display() {
showMarks();
}
}
class Test {
public static void main(String[] args) {
Student s = new Student();
[Link](); // allowed
// [Link] = 90; // ERROR: marks is private
// [Link](); // ERROR: method is private
}
}
Output
Marks: 85
Protected Access Modifier
Variables, methods, and constructors, which are declared protected in a superclass
can be accessed only by the subclasses in other package or any class within the
package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in a interface cannot
be declared protected.
Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.
Example:
class Person {
protected String name = "Sakshi"; // protected data member
protected void showName() { // protected method
[Link]("Name: " + name);
}
}
class Student extends Person {
void display() {
// accessing protected members of parent class
showName();
}
}
class Test {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
Output
Name: Sakshi
Public Access Modifier:
A class, method, constructor, interface, etc. declared public can be accessed from
any other class. Therefore, fields, methods, blocks declared inside a public class can
be accessed from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the
public class still needs to be imported. Because of class inheritance, all public
methods and variables of a class are inherited by its subclasses.
Example:
class College {
public String collegeName = "ABC College"; // public data member
public void showCollege() { // public method
[Link]("College Name: " + collegeName);
}
}
class Test {
public static void main(String[] args) {
College c = new College();
[Link](); // accessible everywhere
}
}
Output
College Name: ABC College
Final Keyword in Java
The final keyword is used to restrict modification.
It can be applied to:
1. Variable
2. Method
3. Class
1. Final Variable Example
A final variable value cannot be changed.
Program
class Demo {
public static void main(String[] args) {
final int MAX = 100;
[Link]("Max value: " + MAX);
// MAX = 200; // ERROR: cannot change final variable
}
}
Output
Max value: 100
2. Final Method Example
A final method cannot be overridden.
class Parent {
final void show() {
[Link]("This is a final method");
}
}
class Child extends Parent {
// void show() { } // ERROR: cannot override final method
}
3. Final Class Example
A final class cannot be inherited.
final class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}
// class Bike extends Vehicle { } // ERROR
Static Keyword in Java
The static keyword is used for class-level members.
Static members belong to the class, not to individual objects.
Example: Static Variable and Static Method
Program
class Counter {
static int count = 0; // static data member
Counter() {
count++;
}
static void showCount() { // static method
[Link]("Count: " + count);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link](); // accessing static method
}
}
Output
Count: 3