Java 面向对象 NO.1

1.类和对象的概念

类是对一类事物进行描述,是抽象的、概念上的定义;

对象是实际存在的该类事物的每个个体,因而也称实例

Java语言中定义类的语法如下:

[修饰符] class 类名
{
    定义构造方法;
    定义属性;
    定义方法;

}

创建两个具体英雄实例,为该实例的 name 属性、 age 属性赋值和 sex 属性赋值,并在控制台输出不同英雄对象的姓名、年龄和性别,调用各自英雄对象的 run()方法。

package ababab;

public class Hero {
	String name;
	int age;
	String sex;
	public void run(int speed) {
		System.out.println(speed+"m/s的速度飞速狂奔");
	}
	public static void main(String[] args) {
		Hero hero1 = new Hero();
		hero1.name = "黑暗游侠";
		hero1.age = 20;
		hero1.sex = "女";
		System.out.println("英雄的名字:"+hero1.name);
		System.out.println("英雄的年龄:"+hero1.age);
		System.out.println("英雄的性别:"+hero1.sex);
		hero1.run(30);
		System.out.println("-------------------");
		
		Hero hero2 = new Hero();
		hero2.name = "撼地神牛";
		hero2.age = 30;
		hero2.sex = "男";
		System.out.println("英雄的名字:"+hero2.name);
		System.out.println("英雄的年龄:"+hero2.age);
		System.out.println("英雄的性别:"+hero2.sex);
		hero2.run(60);
		
	}

}

 

2.对象和引用

类是一种引用数据类型,因此程序中定义的 Hero 类型的变量实际上是一个引用,它被存放在栈内存中,指向实际的 Hero 对象,而真正的 Hero 对象则存放在堆内存中。

 

创建防御塔类(TowerDefence),通过两个坐标属性显示防御塔所在位置 

public  class TowerDefense {
	int x;
	int y;
	public TowerDefense() {
		System.out.println("防御塔已经被实例化了");
	}
	
	public static void main(String[] args) {
		TowerDefense td = new TowerDefense();
		td.x=10;
		td.y=20;
		System.out.println("防御塔横坐标="+td.x+"纵坐标="+td.y);
	}

}

 

 

3.方法详解

方法是类或者对象的行为特征的抽象,是类或对象最重要的组成部分,通过方法可以实现对类的属性的操作。

方法声明格式如下

[<修饰符>] <返回类型> <方法名> ([参数列表]){方法体}

实践,代码如下:

public class tabe {
	String name;
	int age;
	
	public void battle() {
		System.out.println(name+"在肆无忌惮地战斗,他的年龄只有"+age+"可他的血量只有1%了...");
	}
	public static void main(String[] args) {
		tabe xxx = new tabe();
		xxx.name="魔王";
		xxx.age=15;
		xxx.battle();
	}

 

4.方法参数传递

参数的传递是指实际参数向形参值的传递的过程。

 

创建英雄类,在该类中定义战斗方法 battle (),在该方法中 int 类型变量 count,count 初始值为1

count 表示一个计数器,用于记录战斗的次数。

代码如下:

import java.util.Scanner;

public class xswl {
	int output;
	int count=1;
	
	public void battle() {
		output = output-1;
		if(output <= 0) {
			System.out.println("对不起您的英雄已牺牲");
		
			
		}
		System.out.println("第"+count+++"次攻击,您的英雄当前血量"+output);
	}
	public static void main(String[] args) {
		xswl xxx = new xswl();
		Scanner input = new Scanner(System.in);
		System.out.println("请输入英雄的血量");
		xxx.output=input.nextInt();
		for(int i =0;i<6;i++) {
			xxx.battle();
			
		}
		System.out.println("战斗结束后您的英雄血量值="+xxx.output);
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的图书信息管理系统的设计: 1. 创建一个Book类来存储图书信息,包括书名、作者、出版社、ISBN号码等属性。 ```java public class Book { private String title; private String author; private String publisher; private String isbn; public Book(String title, String author, String publisher, String isbn) { this.title = title; this.author = author; this.publisher = publisher; this.isbn = isbn; } // getter and setter methods } ``` 2. 创建一个BookManager类来管理图书信息,包括添加、修改、删除和查询等操作。在这个类中,我们将使用JDBC连接MySQL数据库来实现数据的持久化。 ```java import java.sql.*; import java.util.ArrayList; import java.util.List; public class BookManager { private Connection conn; public BookManager() throws SQLException { String url = "jdbc:mysql://localhost:3306/book_db"; // 数据库地址 String user = "root"; // 数据库用户名 String password = "123456"; // 数据库密码 conn = DriverManager.getConnection(url, user, password); } // 添加图书 public void addBook(Book book) throws SQLException { String sql = "INSERT INTO books (title, author, publisher, isbn) VALUES (?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, book.getTitle()); pstmt.setString(2, book.getAuthor()); pstmt.setString(3, book.getPublisher()); pstmt.setString(4, book.getIsbn()); pstmt.executeUpdate(); } // 修改图书 public void updateBook(Book book) throws SQLException { String sql = "UPDATE books SET title=?, author=?, publisher=? WHERE isbn=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, book.getTitle()); pstmt.setString(2, book.getAuthor()); pstmt.setString(3, book.getPublisher()); pstmt.setString(4, book.getIsbn()); pstmt.executeUpdate(); } // 删除图书 public void deleteBook(String isbn) throws SQLException { String sql = "DELETE FROM books WHERE isbn=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, isbn); pstmt.executeUpdate(); } // 查询所有图书 public List<Book> getAllBooks() throws SQLException { List<Book> books = new ArrayList<>(); String sql = "SELECT * FROM books"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String title = rs.getString("title"); String author = rs.getString("author"); String publisher = rs.getString("publisher"); String isbn = rs.getString("isbn"); Book book = new Book(title, author, publisher, isbn); books.add(book); } return books; } // 根据ISBN号码查询图书 public Book getBookByIsbn(String isbn) throws SQLException { String sql = "SELECT * FROM books WHERE isbn=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, isbn); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { String title = rs.getString("title"); String author = rs.getString("author"); String publisher = rs.getString("publisher"); Book book = new Book(title, author, publisher, isbn); return book; } else { return null; } } // 关闭数据库连接 public void close() throws SQLException { conn.close(); } } ``` 3. 在主函数中,我们可以使用控制台来实现对图书信息的操作,包括添加、修改、删除和查询等。 ```java import java.sql.SQLException; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BookManager manager; try { manager = new BookManager(); } catch (SQLException e) { System.out.println("Failed to connect to database!"); return; } while (true) { System.out.println("Please select an operation:\n1. Add book\n2. Update book\n3. Delete book\n4. List all books\n5. Search book by ISBN\n6. Exit"); int option = scanner.nextInt(); scanner.nextLine(); switch (option) { case 1: System.out.println("Please enter the book information (title, author, publisher, ISBN):"); String[] bookInfo = scanner.nextLine().split(","); if (bookInfo.length != 4) { System.out.println("Invalid input!"); continue; } Book bookToAdd = new Book(bookInfo[0], bookInfo[1], bookInfo[2], bookInfo[3]); try { manager.addBook(bookToAdd); System.out.println("Book added successfully!"); } catch (SQLException e) { System.out.println("Failed to add book!"); e.printStackTrace(); } break; case 2: System.out.println("Please enter the ISBN of the book to update:"); String isbnToUpdate = scanner.nextLine(); Book bookToUpdate; try { bookToUpdate = manager.getBookByIsbn(isbnToUpdate); } catch (SQLException e) { System.out.println("Failed to get book information!"); e.printStackTrace(); continue; } if (bookToUpdate == null) { System.out.println("Book not found!"); continue; } System.out.println("Please enter the updated book information (title, author, publisher):"); String[] bookInfoToUpdate = scanner.nextLine().split(","); if (bookInfoToUpdate.length != 3) { System.out.println("Invalid input!"); continue; } bookToUpdate.setTitle(bookInfoToUpdate[0]); bookToUpdate.setAuthor(bookInfoToUpdate[1]); bookToUpdate.setPublisher(bookInfoToUpdate[2]); try { manager.updateBook(bookToUpdate); System.out.println("Book updated successfully!"); } catch (SQLException e) { System.out.println("Failed to update book!"); e.printStackTrace(); } break; case 3: System.out.println("Please enter the ISBN of the book to delete:"); String isbnToDelete = scanner.nextLine(); try { manager.deleteBook(isbnToDelete); System.out.println("Book deleted successfully!"); } catch (SQLException e) { System.out.println("Failed to delete book!"); e.printStackTrace(); } break; case 4: List<Book> books; try { books = manager.getAllBooks(); } catch (SQLException e) { System.out.println("Failed to get book list!"); e.printStackTrace(); continue; } if (books.isEmpty()) { System.out.println("No books found!"); continue; } System.out.println("All books:"); for (Book book : books) { System.out.printf("%s\t%s\t%s\t%s\n", book.getTitle(), book.getAuthor(), book.getPublisher(), book.getIsbn()); } break; case 5: System.out.println("Please enter the ISBN of the book to search:"); String isbnToSearch = scanner.nextLine(); Book bookToSearch; try { bookToSearch = manager.getBookByIsbn(isbnToSearch); } catch (SQLException e) { System.out.println("Failed to get book information!"); e.printStackTrace(); continue; } if (bookToSearch == null) { System.out.println("Book not found!"); } else { System.out.printf("%s\t%s\t%s\t%s\n", bookToSearch.getTitle(), bookToSearch.getAuthor(), bookToSearch.getPublisher(), bookToSearch.getIsbn()); } break; case 6: try { manager.close(); } catch (SQLException e) { System.out.println("Failed to close database connection!"); e.printStackTrace(); } System.out.println("Goodbye!"); return; default: System.out.println("Invalid option!"); } } } } ``` 在这个程序中,我们使用了异常处理机制来处理可能出现的SQLException异常,以避免程序崩溃。同时,我们也使用了面向对象的思想,将图书信息封装在Book类中,并使用BookManager类来管理图书信息。 需要注意的是,这个程序只是一个简单的示例,实际的图书信息管理系统可能会更加复杂,需要根据具体的需求进行设计和实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值