1.定义一个Person类,包含两个私有的属性(name、age)、一个含参的方法setValue(int age,String name)、一个不含参方法setValue()和一个普通方法tell()。
定义一个测试类Test,实例化一个Person类的对象,名为p;对两个属性赋值并输出结果。
class Person
{
private int age;
private String name;
public void tell()
{
System.out.print("姓名:"+name+",年龄:"+age);
}
public void setValue(int age,String name)
{
this.age=age;
this.name=name;
}
public void setValue()
{
this.name="张三";
this.age=21;
}
}
public class Test
{ public static void main(String[] args)
{
Person p = new Person();
p.setValue(21,"Mary");
p.tell();
}
}
2.定义一个Student类,继承自Person类,含有一个protected访问权限的字符型属性sex,定义Student类的构造方法,并覆写父类的tell()方法,实现对三个属性的赋值和输出。
class Person
{
private int age;
private String name;
public void tell()
{
System.out.print("姓名:"+name+",年龄:"+age);
}
public void setValue(int age,String name)
{
this.age=age;
this.name=name;
}
public void setValue()
{
this.name="张三";
this.age=21;
}
}
class Student extends Person
{
protected char sex;
Student(int age,String name,char sex)
{
super.setValue(age,name);
this.sex=sex;
}
public void tell()
{
super.tell();
System.out.println(",性别:"+sex);
}
}
public class Test
{ public static void main(String[] args)
{
Student s = new Student(20,"Mary",'女');
s.tell();
}
}
3.数据库访问的实现
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException; public class MySQL
{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs =null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentInfo","root","123456");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from student");
while(rs.next())
{
String no = rs.getString(1);
String name = rs.getString("sName");
String sex = rs.getString(3);
int age = rs.getInt(4);
String dept = rs.getString("dept");
System.out.println(no+"__"+name+"__"+sex+" "+age+" "+dept+"__");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(rs !=null) rs.close();
if(stmt!=null) stmt.close();
if(conn !=null) conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
这是重点!这是重点!这是重点!重要的事情说三遍!!!