Cancode Team Lesson Plan
Test Anatomy of a class
classes and objects have the same relation as blueprints to a house
In Java, a class is a blueprint or a template for creating objects which has different attributes and behaviors. Every Java class has a specific structure or anatomy that includes various components.
Here are the different components of a Java class:
Class declaration: Every Java class begins with the declaration of the class name, which should be unique within the package. The syntax for declaring a class is as follows:
Class body: The class body is enclosed in braces {} and contains various components that define the behavior and attributes of the class. The class body consists of the following components:
a. Fields or Instance Variables: Fields are variables that store the state or data of the object, this was covered in unit 2. They can be initialized at the time of declaration or in the constructor. Fields can be of any primitive(int) or reference type(Strings). They are a essential component of a class
Methods: Methods are functions that define the behavior of the object. They can be used to perform certain actions or return a value. Methods can take arguments and can be overloaded, which means there can be multiple methods with the same name but different parameter types. Here's an example:
Constructors are special methods that are used to initialize the state of the object. They have the same name as the class and do not have a return type, by initializing the state of a object the constructor is essentially establishing the field variables
Here's an example:
Not it is important to understand that any field variables, methods, or constructers listed as public is accesible outside the class whereas when it is listed private it is only accesible within the class
-Now generally classes are always made public because it needs to be used
-fields are usually private so that it cannot be tampared with outside the class,
most methods are going to be public but there will be scenarios where you want to make it private, -Constructers need to be public because when creating an object you need to make it public
Inheritance is a way to create new classes based on existing classes. The new class inherits the fields and methods of the existing class, and can also add new fields and methods of its own. In Java, inheritance is implemented using the extends keyword.
In this example, the Dog class extends the Animal class. The Dog class inherits the name field and the speak() method from the Animal class, and also adds its own bark() method.
Polymorphism refers to the ability of objects of different classes to be used interchangeably. This is possible because of inheritance, where a subclass can be used in place of its superclass. Polymorphism is implemented in Java using method overriding and method overloading.
In this example, the Animal class has a speak() method that prints "I am an animal." The Dog class overrides this method with its own implementation that prints "Woof!" When we call speak() on a Dog object, the Dog class's implementation of speak() is called.
The Dog class also has a speak(int times) method that overloads the speak() method. This method takes an integer parameter times and prints "Woof!" that many times. When we call speak(3) on a Dog object, the Dog class's implementation of speak(int times) is called.
HACKS:
Exercise 1: Create a Rectangle class with width and height fields, and getArea() and getPerimeter() methods. Then create a Square class that extends the Rectangle class and has a sideLength field.
Exercise 2: Create a Person class with firstName and lastName fields, and a getFullName() method. Then create a Student class that extends the Person class and has a major field and a getMajor() method.
Exercise 3: Create an Animal class with a speak() method that prints "I am an animal." Then create a Cat class and a Dog class that extend the Animal class and
Format
The typical format of a method header is (). Access modifiers for Java methods can be: public, private, or protected. Return type can be: void, String, boolean, int, double, float, char, etc. Method name can be anything, but usually something descriptive that allows you to infer what the method does. You can have any number of parameters or no parameters.
When a member is declared as "public," it can be accessed from anywhere, including from other classes, even if they are in different packages or assemblies. This means that the member is accessible by any code that can access the class that contains the member.
class Main { public static void main(String[] args) { Person person = new Person(); int age = person.getAge(); // use the age } }
// Examples of method headers: public static void main (String args[]) private String sayHello () protected static int addNums (int a, int b) public void printSum (double a, double b, int c, boolean flag, String text) }}}
Static variables and methods are marked by the keyword static, which means that these are properties of the entire class and not just of one particular object.
Static methods cannot access or change the values of instance variables. Static methods do not have a this reference and cannot use instance variables or call non-static methods.
## 5.8 Scope and Access There are two types of scope: local scope and global scope.Local scope means that a variable can only be used inside a particular method or constructor and not outside. These include our method and constructor parameters and also any variables we declare inside the method or constructor.
Global scope means that a variable or method can be used outside that method or constructor and at least throughout that class. These include our instance variables and also the methods that we write for our class. We declare these directly in the class and not inside a method or constructor.
If there is a local variable (usually a parameter) and a global variable (usually an instance variable) in the same method with the same name, the local variable takes precedence.
This demonstrates that the global variable has global scope, which means it can be accessed from anywhere in the code, while the local variable has local scope, which means it can only be accessed within the method in which it was defined.
The this keyword is a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make. There are three ways to use this:
To refer to an instance variable This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we use this.variableName for the instance variable and simply variableName for the local variable.
As a parameter Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by using objectName.methodName(this).
As a constructor or method call This will allow us to overload our constructors effectively. Inside the overloaded constructors, we can make a call to the full constructor using this() where the parameters include the default values as well. We can also use this way as a method call to call a method inside a method call as well using this.methodName().
The inheritance relationship between a subclass and a superclass is specified in the declaration of the subclass, using the keyword extends. The general format looks like this:
public class Superclass {
//private instance variables
//other data members
//constructors
//public methods
//private methods
}
public class Subclass extends Superclass {
//additional private instance variables
//additional data members
//constructors (Not inherited!)
//additional public methods
//inherited public methods whose implementation is overridden
//additional private methods
}
super
Keywordclass ABC{
public void myMethod()
{
System.out.println("Overridden method");
}
}
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
System.out.println("Overriding method");
}
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod();
}
}
Output:
Class ABC: mymethod()
Class Test: mymethod()
super
super
method, which invokes the superclass constructor.
public SubClass(){
super(); //calls default constructor of superclass
}
A superclass named “Shapes” has a method called “area()”. Subclasses of “Shapes” can be “Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using Inheritance and Polymorphism means, the subclasses can use the “area()” method to find the area’s formula for that shape.
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is 0.5 * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
}
}
Output:
The formula for the area of the Triangle is 0.5 * base * height
The formula for the area of the Circle is 3.14 * radius * radius
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
class Main {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw(); // Output: "Drawing a circle"
s2.draw(); // Output: "Drawing a square"
}
}
In this example, we have a base class Shape with a single method draw() that prints “Drawing a shape” to the console. We then create two subclasses, Circle and Square, that override the draw() method to print “Drawing a circle” and “Drawing a square” respectively.
In the main method, we create two instances of the Shape class, s1 and s2, which are actually instances of the Circle and Square subclasses. When we call the draw() method on these objects, the correct implementation is called based on the actual type of the object, this is run-time polymorphism. The program will output: “Drawing a circle” and “Drawing a square”
In this example, the draw() method is overridden in the subclasses, and this allows for the program to determine which method to use at runtime. This is known as runtime polymorphism or dynamic polymorphism, Because at runtime the JVM determines the actual type of the object and calls the corresponding method.
You can perform Polymorphism in Java via two different methods:
class Shapes {
public void area() {
System.out.println("Find area ");
}
public void area(int r) {
System.out.println("Circle area = "+3.14*r*r);
}
public void area(double b, double h) {
System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b) {
System.out.println("Rectangle area="+l*b);
}
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);
}
}
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is moving");}
}
//Creating a child class
class Car2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("car is running safely");}
public static void main(String args[]){
Car2 obj = new Car2();//creating object
obj.run();//calling method
}
}
Output:
Car is running safely
unkown • 6/16/2025, 12:28:56 PM